为什么max()函数返回的项目小于列表中的另一个项目?

问题描述 投票:1回答:1

这是有问题的代码:

my_list = ['apples', 'oranges', 'cherries', 'banana']
print(max(my_list)

为什么它打印“橙色”而不是“樱桃”?

python max
1个回答
2
投票

字符串按字典顺序相对于彼此排序。 oabc之后。除非到那时为止字符串是相同的,否则长度不是一个因素,在这种情况下,较短的字符串将被判断为“较少”。然后,max()产生词典上最大的字符串(即字典中最远的字符串)。

如果要按长度排序,则必须给max()函数一个键(例如len()函数):

>>> my_list = ['apples', 'oranges', 'cherries', 'banana']
>>> print(max(my_list))
oranges
>>> print(max(my_list, key=len))
cherries
© www.soinside.com 2019 - 2024. All rights reserved.