python - python如何计算列表中的 'max'元素?

标签 python

最近开始学习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/

相关文章:

python - 如何在python中使用MySQLdb创建多个mysql表?

python - 如果对象的图片属于两个不同的来源 - 在 OpenCV 中,如何比较表示同一对象的两个图像?

python - 从字典列表中提取项目

python - 使用 Python OpenCV,您将如何提取特定颜色边界框内的图像区域?

python - Python 中的 Kolmogorov-Smirnov 拟合优度检验

python - 如何从 32 位解释(读取)带符号的 24 位数据

python - 如何在 django mongoengine 中的两个嵌入字段上应用过滤条件?

python - 如何覆盖 modelform 类的 save() 方法并添加缺失信息?

python - 正则表达式,在匹配条上并捕获?

python - 如何从 csv 中读取字节作为字节?