开发者

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

  1. saving the current value of i as w in the lambda function
  2. 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜