Python Max方法给出了错误的结果

时间:2018-04-09 08:23:30

标签: python

我正在尝试使用max方法检查Python列表中最长的单词,但结果对我来说似乎很奇怪。

max(['hello', 'there', 'people'])

返回'there'而不是'people'

这怎么可能?

3 个答案:

答案 0 :(得分:3)

因为您没有指定任何不同的内容,所以它使用字符串的默认比较,这是字典。所以there是最大的,因为它按字母顺序排在最后。

如果您想使用长度,则需要指定。

>>> max(['hello', 'there', 'people'], key=len)
'people'

答案 1 :(得分:1)

除非您另有说明,否则max将使用默认排序方法查找最大值,这意味着按字典顺序排序 - t的字符代码高于p,以便& #39; s返回了什么。如果你想按长度排序,你需要告诉它:

max(['hello', 'there', 'people'], key=len)

答案 2 :(得分:0)

默认情况下max只是测试看哪个字符串比较最高,所以词汇最后一个:

>>> max(['hello', 'there', 'people'])
'there'

要比较长度,您必须指定不同的密钥。

>>> max(['hello', 'there', 'people'], key=len)
'people'
相关问题