Python有一个有序字典。那么有序集呢?


当前回答

有一个pip库是这样做的:

pip install ordered-set

然后你可以使用它:

from ordered_set import OrderedSet

其他回答

答案是否定的,但是您可以使用集合。OrderedDict来自Python标准库,其中只有键(值为None),用于相同的目的。

更新:从Python 3.7(和CPython 3.6)开始,标准dict保证保留顺序,并且比OrderedDict性能更好。(但是,为了向后兼容性,特别是可读性,您可能希望继续使用OrderedDict。)

下面是一个示例,说明如何使用dict作为有序集,在保留顺序的同时过滤掉重复项,从而模拟有序集。使用dict类方法fromkeys()创建一个dict,然后简单地要求返回keys()。

>>> keywords = ['foo', 'bar', 'bar', 'foo', 'baz', 'foo']

>>> list(dict.fromkeys(keywords))
['foo', 'bar', 'baz']

虽然有点晚了,但我已经编写了一个类setlist作为集合扩展的一部分,它完全实现了Sequence和Set

>>> from collections_extended import setlist
>>> sl = setlist('abracadabra')
>>> sl
setlist(('a', 'b', 'r', 'c', 'd'))
>>> sl[3]
'c'
>>> sl[-1]
'd'
>>> 'r' in sl  # testing for inclusion is fast
True
>>> sl.index('d')  # so is finding the index of an element
4
>>> sl.insert(1, 'd')  # inserting an element already in raises a ValueError
ValueError
>>> sl.index('d')
4

GitHub: https://github.com/mlenzen/collections-extended

文档:http://collections-extended.lenzm.net/en/latest/

皮皮 https://pypi.python.org/pypi/collections-extended

在Python 2文档中有一个有序集(可能是新的链接)配方。它运行在Py2.6或更高版本和3.0或更高版本上,无需任何修改。该接口几乎与普通的set完全相同,除了初始化应该使用一个列表。

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

我可以为您提供一个比OrderedSet更好的方法:boltons有一个纯python、2/3兼容的IndexedSet类型,它不仅是一个有序集,而且还支持索引(与列表一样)。

简单的pip install boltons(或复制setutils.py到你的代码库中),导入IndexedSet和:

>>> from boltons.setutils import IndexedSet
>>> x = IndexedSet(list(range(4)) + list(range(8)))
>>> x
IndexedSet([0, 1, 2, 3, 4, 5, 6, 7])
>>> x - set(range(2))
IndexedSet([2, 3, 4, 5, 6, 7])
>>> x[-1]
7
>>> fcr = IndexedSet('freecreditreport.com')
>>> ''.join(fcr[:fcr.index('.')])
'frecditpo'

一切都是唯一的,并保持有序。完全披露:IndexedSet是我写的,但这也意味着如果有任何问题,您可以找我麻烦。:)

有一个pip库是这样做的:

pip install ordered-set

然后你可以使用它:

from ordered_set import OrderedSet