列表的最大值(字符串项)

时间:2014-05-13 16:49:47

标签: python string list python-3.x

Heroes =['Superman','Batman','Dudley Do-Right','Luke Skywalker']
max(Heroes)
'Superman'

有人可以解释为什么上面的结果是'超人'而不是'达德利做对'?

len(Heroes[0])是8

len(Heroes[2])是15

我很困惑。

1 个答案:

答案 0 :(得分:4)

通过词典排序比较字符串,而不是长度。 S位于字母D之后:

>>> 'Superman' > 'Dudley Do-Right'
True

复制max()所做的低效方法是排序输入序列并选择结果的最后一个值。因此,[20, 10, 8, 15]在排序时会将20放在最后,这就是max()返回的内容。对Heroes中的字符串进行排序会导致最后列出Superman

如果您想找到最长的字符串,请使用key argument to max()

max(Heroes, key=len)

此处,Heroes不是直接比较max()中的值,而是将值与key参数的返回值进行比较。现在,len()返回最大值的值将作为最大值返回。

演示:

>>> Heroes = ['Superman', 'Batman', 'Dudley Do-Right', 'Luke Skywalker']
>>> max(Heroes, key=len)
'Dudley Do-Right'