回溯 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/