Does Python have an ordered set?

前端 未结 14 1367
予麋鹿
予麋鹿 2020-11-21 13:20

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

14条回答
  •  后悔当初
    2020-11-21 14:01

    A little late to the game, but I've written a class setlist as part of collections-extended that fully implements both Sequence and 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

    Documentation: http://collections-extended.lenzm.net/en/latest/

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

提交回复
热议问题