最小和最大键如何工作? [英] How do keys work in min and max?
问题描述
我按照以下顺序执行语句:
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.
关于min和max的python文档非常粗略.
The python documentation on min and max is pretty sketchy.
有人可以向我解释密钥"的工作原理吗?
Can anyone explain to me how the "key" works?
推荐答案
key
参数的解释
密钥的工作方式如下:
Explanation of the key
argument
Key works like this:
a_list = ['apple', 'banana', 'canary', 'doll', 'elephant']
min(a_list, key=len)
返回'doll'
和
max(a_list, key=len)
返回'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.
如果您的函数返回一个布尔值(如您的布尔值),则它将最小返回True或False的最小值(即False)中的第一个(即6)或max(True)的最小值中的第一个. 0.
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.
要查看此内容
>>> 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}
为什么?
>>> min([True, False])
False
>>> max([True, False])
True
说明
为什么True
大于False
?
>>> True == 1
True
>>> False == 0
True
>>> issubclass(bool, int)
True
事实证明,True
和False
与1
和0
密切相关.他们甚至分别评价相同.
It turns out that True
and False
are very closely related to 1
and 0
. They even evaluate the same respectively.
这篇关于最小和最大键如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!