给定一个元组列表,我可以通过以下方式找到元组列表中第一个元素的最大值:
>>> a,b,c,d = (4,"foo"),(9,"bar"),(241,"foobar"), (1,"barfoo")
>>> print max([a,b,c,d])
(241,"foobar")
但是如何找到第二个元素的最大值呢?字符串的最大值如何?
使用key
参数:
import operator
max([a, b, c, d], key=operator.itemgetter(1))
字符串的max()
是基于字符串的字节值;'a'
高于'A'
因为ord('a')
高于ord('A')
。
对于您的示例输入,(241,"foobar")
仍然是最大值,因为'f'
> 'b'
and'foobar'
比'foo'
, 和'b'
>更长(更多值) ''
(在较长字符串中b
的字母之后的字符)。foo
更短的是使用 lambda 作为可调用对象
max([a, b, c, d], key=lambda t: t[1])