python max()字符串的比较_为什么python max('a',5)返回字符串值?

Tracing back a ValueError: cannot convert float NaN to integer I found out that the line:

max('a', 5)

max(5, 'a')

will return a instead of 5.

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).

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?

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

min('a', 5)

min(5, 'a')

returns 5.

解决方案

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

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

[5, 'a']

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.

Bold emphasis mine.

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 "", line 1, in

TypeError: unorderable types: str() > int()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值