Python 2如何比较字符串和int?为什么列表比较大于数字,而元组大于列表?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python 2如何比较字符串和int?为什么列表比较大于数字,而元组大于列表?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1941字,纯文字阅读大概需要3分钟。
内容图文
![Python 2如何比较字符串和int?为什么列表比较大于数字,而元组大于列表?](/upload/InfoBanner/zyjiaocheng/717/695c313054244b6da687f77d965a0773.jpg)
以下代码段使用输出(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语言版本之间是否存在差异?
解决方法:
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 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()
内容总结
以上是互联网集市为您收集整理的Python 2如何比较字符串和int?为什么列表比较大于数字,而元组大于列表?全部内容,希望文章能够帮你解决Python 2如何比较字符串和int?为什么列表比较大于数字,而元组大于列表?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。