Heroes =['Superman','Batman','Dudley Do-Right','Luke Skywalker']
max(Heroes)
'Superman'
有人可以解释为什么上面的结果是'超人'而不是'达德利做对'?
len(Heroes[0])
是8
len(Heroes[2])
是15
我很困惑。
答案 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'