以下代码段使用输出进行注释(如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
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么输出是这样的?
今天早些时候我问了一个问题,因为我无法真正理解使用丰富比较方法的比较运算符的实现。感谢您对已接受的答案很好地解释了两者之间的差异。
基本上,据我所知,Python 3 停止使用__cmp__()魔法方法。从现在开始,
当操作数没有有意义的自然排序时,排序比较运算符(<、<=、>=、>)会引发 TypeError 异常。
因此,我认为这OrderedDict是有效的。但是,令我惊讶的是,
d1 = OrderedDict([(1,1)])
d2 = OrderedDict([(2,2)])
>>> dict1 < dict2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'collections.OrderedDict' and 'collections.OrderedDict'
>>> dict1.__lt__(dict2)
NotImplemented
Run Code Online (Sandbox Code Playgroud)
那么,为什么不OrderedDict实现比较运算符呢?
请注意,在链接问题的答案的评论中,我们开始谈论该主题。有下划线的一件事是,为什么假设插入顺序是您想要比较事物的方式?您始终可以实现自己的方式来明确比较它们。
那为什么(即使在 Python 3 中),
list1 = [1,2,3]
list2 = [4,5,6]
>>> list1 < list2
True
Run Code Online (Sandbox Code Playgroud)
不是类似的情况吗?