简体   繁体   English

在包含字符串和整数的列表上使用max()

[英]Using max() on a list containing strings and integers

When I try to call the max() function on a list which contains a combination of integers and strings, it always returns a string, in Python 2.x 当我尝试在包含整数和字符串组合的列表上调用max()函数时,在Python 2.x中它总是返回一个字符串

For example, 例如,

#input
li = [2, 232322, 78, 'python', 77]
max(li)

#output
'python'

What seems to be the logic behind this? 这背后的逻辑似乎是什么? How does Python compare a string with an integer? Python如何比较字符串和整数?

In python2, strings and numbers compare in arbitrary but consistent order. 在python2中,字符串和数字以任意但一致的顺序进行比较。

See Comparisons 查看比较

Objects of different types, except different numeric types and different string types, never compare equal; 不同类型的对象(不同的数字类型和不同的字符串类型除外)绝不会相等。 such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result 这样的对象被一致地但任意地排序(以便对异构数组进行排序会产生一致的结果

In python3, this raises a type error. 在python3中,这引发类型错误。

TypeError: unorderable types: str() > int()

The comparision between strings and numbers is undefined. 字符串和数字之间的比较是不确定的。 It depends on the version of python. 它取决于python的版本。 Strings are either always larger than any number or lower. 字符串总是大于或小于任何数字。

The manual states, that in CPython different objects are compared after their type name, if no other comparision is defined. 手册指出,在CPython中,如果未定义其他比较,则在其对象名称之后比较不同的对象。

In Python 2.x The max() and min() functions first internally sort the list, resulting in a list similar to the output of list.sort() and then outputs the last (max) and first(min) item of the list- 在Python 2.x中,max()和min()函数首先在内部对列表进行排序,生成类似于list.sort()输出的列表,然后输出该列表的最后一个(max)和first(min)项。清单-

>>> li = [2, 232322, 78, 'python', 77]
>>> max(li)
'python'
>>> min(li)
2

As you can see below if you sort the list the first and last item in the list are the result produce by min and max functions 如下所示,如果对列表进行排序,则列表中的第一项和最后一项是最小和最大函数产生的结果

>>> li = [2, 232322, 78, 'python', 77]
>>> li.sort()
>>> print li
[2, 77, 78, 232322, 'python']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM