Does Python have an ordered set?

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

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

14条回答
  •  孤独总比滥情好
    2020-11-21 13:39

    If you're using the ordered set to maintain a sorted order, consider using a sorted set implementation from PyPI. The sortedcontainers module provides a SortedSet for just this purpose. Some benefits: pure-Python, fast-as-C implementations, 100% unit test coverage, hours of stress testing.

    Installing from PyPI is easy with pip:

    pip install sortedcontainers
    

    Note that if you can't pip install, simply pull down the sortedlist.py and sortedset.py files from the open-source repository.

    Once installed you can simply:

    from sortedcontainers import SortedSet
    help(SortedSet)
    

    The sortedcontainers module also maintains a performance comparison with several alternative implementations.

    For the comment that asked about Python's bag data type, there's alternatively a SortedList data type which can be used to efficiently implement a bag.

提交回复
热议问题