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

2024-10-01 19:22:47 发布

您现在位置:Python中文网/ 问答频道 /正文

以下代码段用输出(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语言的不同版本之间有区别吗?

Tags: 规范com语言falsetrueonas代码段
2条回答

字符串在词汇上比较,不同的类型按其类型的名称比较("int"<;"string")。3.x通过使第二点不可比较来确定第二点。

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

一个例外是旧样式的类总是先于新样式的类。

>>> 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 specificationlanguage 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?

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

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

相关问题 更多 >

    热门问题