以下代码段用输出(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
有人能解释为什么输出是这样吗?
字符串在词汇上比较,不同的类型按其类型的名称比较(
"int"
<;"string"
)。3.x通过使第二点不可比较来确定第二点。从python 2 manual:
当您订购两个字符串或两个数字类型时,将按预期的方式进行排序(字符串的字典式排序,整数的数字排序)。
当您订购数值型和非数值型时,数值型优先。
如果您订购两种不兼容的类型,而这两种类型都不是数字,则它们按其类型名的字母顺序排列:
一个例外是旧样式的类总是先于新样式的类。
有no language specification。language reference说:
所以这是一个实现细节。
我不能回答这个问题,因为我只使用了正式的CPython实现,但是还有Python的其他实现,比如PyPy。
在Python3.x中,行为已被更改,因此尝试对整数和字符串排序将引发错误:
相关问题 更多 >
编程相关推荐