I have a question when I use Python enumerate to find the max value.

Asked 2 years ago, Updated 2 years ago, 16 views

queue = [1, 2, 3, 4] #queue that contains only priority values.

queue = [(i, idx) for idx, i in enumerate(queue)] # (priority, index) This is the queue saved in the form.

When trying to find the element with the highest priority in the above state, it says max(queue, key=rambdax: x[0])[0] and I wonder why the last [0] is needed.

max(queue, key=lambdax:x[0]) is stored in the (priority, index) form, so you can find the maximum value of the priority, which is the first factor, right?

Additionally, I wonder how the results are different when writing max(queue, key=lambdax: x[0][0]).

Thank you for your answer.

python

2022-09-20 19:57

1 Answers

queue = [(i, idx) for idx, i in enumerate(queue)] where the queue value is It looks like [(1,0),(2,1),(3,2),(4,3)]

max(queue, key=lambdax:x[0]) derives the max value based on the first value for the tuple in the queue, so the result of that max function is (4,3), so the first value is taken from this value.

If the value for this tuple is variable differently than when the list was first created, you must write a = max(queue, key = lambda x: x[0]); print (max(a)).

Therefore, if you assume that x[0][0] is a (1,0) tube in the question, an error will occur.

Thank you


2022-09-20 19:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.