Python有一个ordered dictionary。有序集呢?

最佳答案

为此有一个ordered set(可能是new link)食谱,可从Python 2 Documentation引用。无需修改即可在Py2.6或更高版本以及3.0或更高版本上运行。该接口(interface)几乎与普通集合完全相同,不同之处在于初始化应使用列表进行。

OrderedSet([1, 2, 3])

这是一个MutableSet,因此.union的签名与set的签名不匹配,但是由于它包含__or__,因此可以轻松添加类似的内容:
@staticmethod
def union(*sets):
    union = OrderedSet()
    union.union(*sets)
    return union

def union(self, *sets):
    for set in sets:
        self |= set

10-07 19:09
查看更多