How does this max() expression in Python work?
Here's the code:
a = [1,2,3,4]
b = {}
b[1] = 10
b[2] = 8
b[3] = 7
b[4] = 5
print max(a,key=lambda w: b[w])
This prints out 1
.
I don't understand how max(a,key=lambda w: b[w])
is being evaluated here though; I'm guessing for each value i in a, it finds the corresponding value b[i] by
- saving the current value of i as w in the lambda function
- getting the corresponding value from b[i] and storing it in key.
But then why does it print out 1 instead of 11? Or why doesn't it print out 10, since that's really the maximum numbe开发者_JAVA技巧r?
max(a,...)
is always going to return an element of a
. So the result will be either 1,2,3, or 4.
For each value w
in a
, the key value is b[w]
. The largest key value is 10, and that corresponds with w
equalling 1. So max(a,key=lambda w: b[w])
returns 1.
Try:
a = [1,2,3,4]
b = {}
b[1] = 10
b[2] = 8
b[3] = 7
b[4] = 5
c = a + b.values()
print max(*c)
精彩评论