相关疑难解决方法(0)

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

以下代码段使用输出进行注释(如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实现之间是否存在差异?
  • Python语言版本之间是否存在差异?

python comparison types python-2.x

172
推荐指数
2
解决办法
8万
查看次数

为什么 OrderedDict 没有实现比较运算符

今天早些时候我问了一个问题,因为我无法真正理解使用丰富比较方法的比较运算符的实现。感谢您对已接受的答案很好地解释了两者之间的差异。

基本上,据我所知,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)

不是类似的情况吗?

python comparison-operators python-3.x

2
推荐指数
1
解决办法
800
查看次数