def func(p):
return p.totalScore
現在max成為:
max(players, key=func)
但是由於def語句是復合語句,它們不能用於需要表達式的地方,這就是為什么有時使用lambda的原因。
注意,lambda等同於你在一個def的return語句中。因此,不能在lambda中使用語句,只允許表達式。
max是什么?
max(a, b, c, …[, key=func]) -> value
With a single iterable argument, return its largest item. With two or
more arguments, return the largest argument.
因此,它只返回最大的對象。
**How *key* works?** 默認情況下,Python 2鍵基於對象的類型(例如字符串總是大於整數)基於 set of rules比較項目。要在比較之前修改對象或基於特定屬性/索引進行比較,必須使用關鍵參數。
實施例1:
一個簡單的例子,假設你有一個字符串形式的數字列表,但你想比較這些項目的整數值。
```python >>> lis = ['1','100','111','2'] ```這里max使用它們的原始值比較項目(字符串是字典比較,所以你會得到’2’作為輸出):
```python >>> max(lis) '2' ```要通過它們的整數值比較項目,請使用帶有簡單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')
比較包含不同類型對象的iterable中的項目:
混合項目列表:
>>> lis = ['1','100','111','2', 2, 2.57]
In Python 2 it is possible to compare items of two different types:
```python >>> max(lis) # works in Python 2 '2' ``` ```python >>> 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()
但這工作,因為我們比較每個對象的整數版本:
```python >>> max(lis, key=lambda x: int(x)) # or simply `max(lis, key=int)` >>> '111' ```敲黑板,所以,如果要返回字典中value最大的item,只需如下操作:
>>> prices = {
... 'A':123,
... 'B':450.1,
... 'C':12,
... 'E':444,
... }
>>> max(prices.items(),key=lambda x:x[1])
('B', 450.1)
>>>
- Reference: python max函數使用’key’和lambda表達式
