问题
I run through the following sequence of statements:
>>> a = range(10)
>>> min(a, key=lambda x: x < 5.3)
6
>>> max(a, key=lambda x: x < 5.3)
0
The min and max give the exact opposite of what I was expecting.
The python documentation on min and max is pretty sketchy.
Can anyone explain to me how the "key" works?
回答1:
Explanation of the key
argument
Key works like this:
a_list = ['apple', 'banana', 'canary', 'doll', 'elephant']
min(a_list, key=len)
returns 'doll'
, and
max(a_list, key=len)
returns 'elephant'
You provide it with a function, and it uses the minimum or maximum of the results of the function applied to each item to determine which item to return in the result.
Application
If your function returns a boolean, like yours, for min it'll return the first of the minimum of True or False, (which is False) which would be 6 or the first of the max (True) which would be 0.
To see this:
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> import pprint
>>> pprint.pprint(dict((i, i<5.3) for i in a))
{0: True,
1: True,
2: True,
3: True,
4: True,
5: True,
6: False,
7: False,
8: False,
9: False}
Why?
>>> min([True, False])
False
>>> max([True, False])
True
Explanation
Why is True
greater than False
?
>>> True == 1
True
>>> False == 0
True
>>> issubclass(bool, int)
True
It turns out that True
and False
are very closely related to 1
and 0
. They even evaluate the same respectively.
回答2:
because all values are either True
or False
. So the first one of each is chosen.
min([True, 1, False, 0])
will return False
instead of 0
because both have the same value but False
happens first
Your code uses a key
function with only boolean values so, for min
, the first False
happens at the number 6
. So it is the chosen one.
What you probably want to do is:
min(x for x in range(10) if x < 5.3)
来源:https://stackoverflow.com/questions/21543040/how-do-keys-work-in-min-and-max