Python 有有序集吗? [英] Does Python have an ordered set?

查看:50
本文介绍了Python 有有序集吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 有一个有序字典.有序集呢?

Python has an ordered dictionary. What about an ordered set?

推荐答案

有一个有序集(可能 rerel 链接为 recipe="new"">errel>这是从 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

这篇关于Python 有有序集吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆