python - Python 2 如何比较字符串和整数?为什么列表比较大于数字,而元组大于列表?

以下代码段使用输出 (as seen on ideone.com) 进行了注释:

print "100" < "2"      # True
print "5" > "9"        # False

print "100" < 2        # False
print 100 < "2"        # True

print 5 > "9"          # False
print "5" > 9          # True

print [] > float('inf') # True
print () > []          # True

有人可以解释为什么输出是这样的吗?


实现细节

  • 这种行为是语言规范规定的,还是由实现者决定的?
  • 任何主要的 Python 实现之间是否存在差异?
  • Python 语言版本之间是否存在差异?

最佳答案

来自 python 2 manual :

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

当您对两个字符串或两个数字类型进行排序时,排序是以预期的方式完成的(字符串的字典顺序,整数的数字排序)。

当您订购数字和非数字类型时,数字类型排在第一位。

>>> 5 < 'foo'
True
>>> 5 < (1, 2)
True
>>> 5 < {}
True
>>> 5 < [1, 2]
True

当您订购两个都不是数字的不兼容类型时,它们按其类型名称的字母顺序排序:

>>> [1, 2] > 'foo'   # 'list' < 'str' 
False
>>> (1, 2) > 'foo'   # 'tuple' > 'str'
True

>>> class Foo(object): pass
>>> class Bar(object): pass
>>> Bar() < Foo()
True

一个异常(exception)是旧式类总是在新式类之前。

>>> class Foo: pass           # old-style
>>> class Bar(object): pass   # new-style
>>> Bar() < Foo()
False

Is this behavior mandated by the language spec, or is it up to implementors?

有no language specification . language reference说:

Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily.

所以这是一个实现细节。

Are there differences between any of the major Python implementations?

这个我无法回答,因为我只用过官方的CPython实现,但是还有其他Python的实现比如PyPy。

Are there differences between versions of the Python language?

在 Python 3.x 中,行为已更改,因此尝试对整数和字符串进行排序会引发错误:

>>> '10' > 5
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    '10' > 5
TypeError: unorderable types: str() > int()

https://stackoverflow.com/questions/3270680/

相关文章:

linux - 否定 bash 脚本中的 if 条件

bash - 为什么 $$ 返回与父进程相同的 id?

python - 在列表中查找属性等于某个值的对象(满足任何条件)

python - 为什么提早返回比其他方法慢?

linux - 如何更改 bash 历史完成以完成已经上线的内容?

python - 使用 groupby 获取组中具有最大值的行

python - 什么是 "first-class"对象?

linux - 如何请求文件但不使用 Wget 保存?

linux - 在管道 grep 到 grep 后保留颜色

python - sum() 之类的函数是什么,但用于乘法?产品()?