Python有有序集吗?
问题描述
Python 有一个有序字典.那么有序集合呢?
Python has an ordered dictionary. What about an ordered set?
解决方案
有一个有序集(可能的新链接)配方这是从 Python 2 文档 中引用的.这可以在 Py2.6 或更高版本以及 3.0 或更高版本上运行,无需任何修改.接口几乎和普通集合一样,只是初始化应该用一个列表来完成.
There is an ordered set (possible new link) recipe for this which is referred to from the Python 2 Documentation. This runs on Py2.6 or later and 3.0 or later without any modifications. The interface is almost exactly the same as a normal set, except that initialisation should be done with a list.
OrderedSet([1, 2, 3])
这是一个 MutableSet,因此 .union
的签名与 set 的签名不匹配,但由于它包含 __or__
,因此可以轻松添加类似的内容:
This is a MutableSet, so the signature for .union
doesn't match that of set, but since it includes __or__
something similar can easily be added:
@staticmethod
def union(*sets):
union = OrderedSet()
union.union(*sets)
return union
def union(self, *sets):
for set in sets:
self |= set
相关文章