# others - python max函数使用'key'和lambda表达式

``````
def winner():

w = max(players, key=lambda p: p.totalScore)

``````

• `max`函数的工作原理？ 它的参数是什么？ 我查看了文档，但无法理解，
• max函数中关键字`key`的用法？ 我知道它在sort函数的上下文中使用
• lambda表达式的含义？ 它们如何工作？

`lambda`是匿名函数，它等效于：

``````
def func(p):

return p.totalScore

``````

``````
max(players, key=func)

``````

`max`的工作原理？

max(a ,b ,c ,... [ ,key=func] ) - > value

`key`如何工作？

``````
>>> lis = ['1', '100', '111', '2']

``````

``````
>>> max(lis)

'2'

``````

``````
>>> max(lis, key=lambda x:int(x)) # compare `int` version of each item

'111'

``````

``````
>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]

``````

``````
>>> max(lis)

(4, 'e')

``````

``````
>>> max(lis, key = lambda x: x[1])

(-1, 'z')

``````

``````
lis = ['1','100','111','2', 2, 2.57]

``````

``````
>>> max(lis) # works in Python 2

'2'

>>> max(lis, key=lambda x: int(x)) # compare integer version of each item

'111'

``````
``````
>>> 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'

``````

max的强化版本：

``````
def max(items, key=lambda x: x):

current = item[0]

for item in items:

if key(item) > key(current):

current = item

return current

``````

``````
>>> ident = lambda x: x

>>> ident(3)

3

>>> ident(5)

5

>>> times_two = lambda x: 2*x

>>> times_two(2)

4

``````

`max`函数用于获取`iterable`的最大值。

``````
max(iterable[, key=func]) -> value

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.

``````

`lambda`是一个python关键字，充当伪函数，因此，当你将`player`对象传递给它时，它将返回`player.totalScore` ，因此，传递给函数max的iterable将根据player对象的key totalScore进行排序，将返回最大`totalScore``player`

``````
max(1, 3, 5, 7)

>>>7

max([1, 3, 5, 7])

>>>7

people = [('Barack', 'Obama'), ('Oprah', 'Winfrey'), ('Mahatma', 'Gandhi')]

max(people, key=lambda x: x[1])

>>>('Oprah', 'Winfrey')

``````