lambda
为匿名函数,相当于:
def func(p):
return p.totalScore
现在max
变成了:
max(players, key=func)
但是,由于def
个语句是复合语句,它们不能用于需要表达式的地方,这就是为什么有时使用lambda
个语句的原因.
请注意,lambda
相当于您在返回值为def
的语句中输入的值.因此,您不能在lambda
内使用语句,只允许使用表达式.
What does 100 do?
max(a, b, c, ...[, key=func]) -> value
使用单个可迭代参数,返回其最大项.带两个或两个
参数越多,返回的参数越大.
因此,它只返回最大的对象.
How does 100 work?
在Python2中,默认情况下key
会根据对象的类型(例如字符串总是大于整数)根据set of rules来比较项目.
要在比较之前修改对象,或基于特定属性/索引进行比较,必须使用key
参数.
示例1:
举一个简单的例子,假设您有一个字符串形式的数字列表,但您希望通过它们的整数值来比较这些项.
>>> lis = ['1', '100', '111', '2']
这里max
使用它们的原始值来比较项目(字符串按字典顺序进行比较,因此您将得到'2'
作为输出):
>>> max(lis)
'2'
要通过整数值比较项目,请使用key
和简单的lambda
:
>>> max(lis, key=lambda x:int(x)) # compare `int` version of each item
'111'
示例2:将max
应用于元组列表.
>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]
默认情况下,max
将按第一个索引比较项目.如果第一个索引相同,则它将比较第二个索引.与我的示例一样,所有项目都有一个惟一的第一个索引,因此您将得到以下答案:
>>> max(lis)
(4, 'e')
但是,如果你想用索引1的值来比较每一项呢?简单:使用lambda
:
>>> max(lis, key = lambda x: x[1])
(-1, 'z')
Comparing items in an iterable that contains objects of different type:
混合项目列表:
lis = ['1','100','111','2', 2, 2.57]
In Python 2 it is possible to compare items of two different types:
>>> max(lis) # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x)) # compare integer version of each item
'111'
But in Python 3 you can't do that any more:
>>> lis = ['1', '100', '111', '2', 2, 2.57]
>>> max(lis)
Traceback (most recent call last):
File "<ipython-input-2-0ce0a02693e4>", line 1, in <module>
max(lis)
TypeError: unorderable types: int() > str()
但这是可行的,因为我们正在比较每个对象的整数版本:
>>> max(lis, key=lambda x: int(x)) # or simply `max(lis, key=int)`
'111'