为什么python max('a',5)返回字符串值? [英] Why does python max('a', 5) return the string value?

查看:93
本文介绍了为什么python max('a',5)返回字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

将返回a而不是5.

在上述情况下,我使用示例字符串a,但在我的实际情况下,字符串为NaN(拟合过程未能收敛的结果).

In the above case I used the example string a but in my actual case the string is a NaN (the result of a fitting process that failed to converge).

此行为背后的原理是什么?为什么python无法自动识别出那里有一个字符串并且应该返回数字?

What is the rationale behind this behaviour? Why doesn't python recognize automatically that there's a string there and that it should return the number?

更令人好奇的是,由于以下原因,min() 能够按预期工作:

Even more curious is that min() does work as expected since:

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

返回5.

推荐答案

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

In Python 2, numeric values always sort before strings and almost all other types:

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

然后,数字被认为比字符串小 .使用max()时,表示字符串是从数字中选取的.

Numbers then, are considered smaller than strings. When using max(), that means the string is picked over a number.

数字较小是一个任意的实现选择.请参见 比较文档:

That numbers are smaller is an arbitrary implementation choice. See the 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代替:

Python 2 tried real hard to make heterogenous types sortable, which has caused a lot of hard to debug problems, such as programmers trying to compare integers with strings and getting unexpected results. Python 3 corrected this mistake; you'll get a TypeError instead:

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

我已经在其他地方写了有关订购规则,甚至

I've written elsewhere about the ordering rules, and even re-implemented the Python 2 rules for Python 3, if you really wanted those back.

这篇关于为什么python max('a',5)返回字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆