为什么 python max('a', 5) return 是字符串值?

Why does python max('a', 5) return the string value?

回溯 ValueError: cannot convert float NaN to integer 我发现那行:

max('a', 5)
max(5, 'a')

将 return a 而不是 5.

在上面的例子中,我使用了示例字符串 a,但在我的实际情况中,字符串是 NaN(未能收敛的拟合过程的结果)。

这种行为背后的基本原理是什么?为什么 python 不能自动识别那里有一个字符串并且它应该 return 数字?

更奇怪的是 min() 是否按预期工作,因为:

min('a', 5)
min(5, 'a')

returns 5.

在 Python 2 中,数值总是排在字符串和几乎所有其他类型之前:

>>> sorted(['a', 5])
[5, 'a']

然后,数字被认为比字符串。当使用 max() 时,这意味着字符串是在数字上选取的。

数字更小是一个任意的实现选择。见 Comparisons documentation:

The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily.

大胆强调我的。

Python 2 非常努力地使异构类型可排序,这导致了很多难以调试的问题,例如程序员试图将整数与字符串进行比较并得到意想不到的结果。 Python 3更正了这个错误;你会得到 TypeError 而不是:

>>> max(5, 'a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()

我已经 written elsewhere about the ordering rules, and even re-implemented the Python 2 rules for Python 3,如果你真的想要那些回来。

在 CPython 2.x 中,字符串总是大于数字,这就是您看到这些行为的原因。

OTOH,我不明白为什么你认为 5 "obviously" 大于 "a"...为了方便起见,不同类型的值是可比较的(例如,如果你正在构建一个 RB具有异类键的树,您希望所有内容都具有可比性),并且此类比较确实定义了严格的弱排序,但是类型间比较无意以任何方式变得合理(您如何将数字与字符串或对象进行比较? ), 恰到好处。