Max()函数在Python 3.4中没有返回最大值

Mac*_*ndo -3 python max python-3.x

为什么max()Python 3.4 中的函数在值列表中给出的值小于预期值?

示例1,其中期望值为'marco':

>>> max('zara', 'marco')
'zara'
Run Code Online (Sandbox Code Playgroud)

示例2,其中期望值为'cherries':

>>> max('apples', 'oranges', 'cherries', 'banana')
'oranges'
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 11

字符串按字典顺序排列,而不是按大小排序.

如果你想要最长的字符串,你需要告诉max()它使用它作为键:

max(sequence, key=len)
Run Code Online (Sandbox Code Playgroud)

演示:

>>> max('zara', 'marco')
'zara'
>>> max('zara', 'marco', key=len)
'marco'
>>> max('apples', 'oranges', 'cherries', 'banana')
'oranges'
>>> max('apples', 'oranges', 'cherries', 'banana', key=len)
'cherries'
Run Code Online (Sandbox Code Playgroud)

  • @Tommy:跟上来,很久以前就已经纠正了错字!:-P (2认同)