python中str和int区别_Python 2如何比较字符串和int?为什么列表比...

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

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

'10' > 5

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值