python - 为什么 python max ('a' , 5) 返回字符串值?

标签 python max min

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

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

将返回 a 而不是 5。

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

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

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

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

返回 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 ,甚至 re-implemented the Python 2 rules for Python 3 ,如果您真的想要这些。

关于python - 为什么 python max ('a' , 5) 返回字符串值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28258531/

相关文章:

python - 将最大值应用于数据框的每一列

c - 最小-最大选择——那是什么算法?

python - 两个向量之间的numpy min()?

python - 在线图中放置间隙/中断

python - 在 Google 应用引擎中打印新行

python - 相同的 Python 代码对相同的输入字符串返回不同的结果

java - 在二维数组中查找行的最大值和列的最小值

scala - 如何在Scala中的列表中找到最大值的索引?

python - Tensorflow 服务类型 : Object is not of expected type: uint8

awk - 在周期中划分一列并在 awk 中打印每个列的最小值最大值