为什么 OrderedDict 没有实现比较运算符
Why is OrderedDict not implementing comparison operators
今天早些时候我问了一个 因为我无法真正理解使用丰富比较方法的比较运算符的实现。谢谢您对公认的答案很好地解释了两者之间的区别。
基本上,据我了解,Python 3 停止使用__cmp__()
魔法方法。从现在开始,
The ordering comparison operators (<, <=, >=, >) raise a TypeError
exception when the operands don’t have a meaningful natural ordering.
因此,我认为 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
那么,为什么 OrderedDict
没有实现比较运算符?
请注意,在链接问题答案的评论中,我们开始讨论该主题。强调的一件事是,为什么假设插入顺序是您想要比较事物的方式?您始终可以实现自己的方式来显式比较它们。
那为什么(即使在Python 3),
list1 = [1,2,3]
list2 = [4,5,6]
>>> list1 < list2
True
是不是类似的情况?
A "meaningful natural ordering"指的是"natural"决定两个对象中哪个更大的方法。它不是指对象是否是有序集合。
OrderedDict 可能对其条目进行排序,但两个 OrderedDicts 之间没有自然的排序关系。
@scharette,我同意在某些角度下 OrderedDict 确实看起来像一个访问时间为 O(1) 的链表。 cpython 的开发人员在 OrderedDict 的 C implementation 的评论中分享了这一观点。
我对你的问题的回答很简单。 没有人想到那么远 )
original proposal 中没有比较运算符。
未通过 bugs.python.org nor as a PEP
添加任何提案
如果您觉得值得向 OrderedDict 添加比较运算符,请在 https://bugs.python.org/
提交增强请求
今天早些时候我问了一个
基本上,据我了解,Python 3 停止使用__cmp__()
魔法方法。从现在开始,
The ordering comparison operators (<, <=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering.
因此,我认为 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
那么,为什么 OrderedDict
没有实现比较运算符?
请注意,在链接问题答案的评论中,我们开始讨论该主题。强调的一件事是,为什么假设插入顺序是您想要比较事物的方式?您始终可以实现自己的方式来显式比较它们。
那为什么(即使在Python 3),
list1 = [1,2,3]
list2 = [4,5,6]
>>> list1 < list2
True
是不是类似的情况?
A "meaningful natural ordering"指的是"natural"决定两个对象中哪个更大的方法。它不是指对象是否是有序集合。
OrderedDict 可能对其条目进行排序,但两个 OrderedDicts 之间没有自然的排序关系。
@scharette,我同意在某些角度下 OrderedDict 确实看起来像一个访问时间为 O(1) 的链表。 cpython 的开发人员在 OrderedDict 的 C implementation 的评论中分享了这一观点。
我对你的问题的回答很简单。 没有人想到那么远 )
original proposal 中没有比较运算符。
未通过 bugs.python.org nor as a PEP
添加任何提案如果您觉得值得向 OrderedDict 添加比较运算符,请在 https://bugs.python.org/
提交增强请求