tags:

views:

233

answers:

2

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 number?

+6  A: 

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.

unutbu
A: 

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)
enrnpfnfp
that's so bad, I don't even want to downvote it.
SilentGhost
why is bad? you can also do the same without concatenate the values if a and b are huge.
enrnpfnfp
because it's so far from what OP is trying to do, that it's just frustrating
SilentGhost
-1 is warranted just for the max(*c)
John Machin
why the max(*c)? Are you trying to dereference c?
Goose Bumper
@Goose Bumper: if `c` refers to `[1, 42, 666]` then `max(*c)` is equivalent to `max(1, 42, 666)` (see `http://docs.python.org/reference/expressions.html#calls`). My downvote is because that is obscure and inefficient as well; `max(c)` gives the same result (see `http://docs.python.org/library/functions.html#max`).
John Machin