最近开始学习python,遇到一个与列表相关的疑问。
这是我的示例列表。
>>>list1
[1, 2.3, 4, 'a', 300, 'b']
>>> max(list1)
'b'
尽管“b”的 ascii 值为 98,远小于其相邻元素 300,但 python 返回“b”作为 MAX 元素。
那么,有人请告诉我python如何计算最大元素吗?
最佳答案
除了比较数字与数字以及字符串类型与字符串类型(如您所期望的那样工作)之外,“奇怪”的比较是一致但任意的。某些类型还具有预定义的比较函数,这些函数也会覆盖此规则:例如 None
始终比较少于其他所有内容。
请参阅语言引用:https://docs.python.org/2/library/stdtypes.html#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). Furthermore, some types (for example, file objects) support only a degenerate notion of comparison where any two objects of that type are unequal. Again, such objects are ordered arbitrarily but consistently. The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex number.
如果您使用 CPython,它有更严格定义的比较:
CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.
关于python - python如何计算列表中的 'max'元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29503237/