Does Python have an ordered set?

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

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

14条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 13:52

    Implementations on PyPI

    While others have pointed out that there is no built-in implementation of an insertion-order preserving set in Python (yet), I am feeling that this question is missing an answer which states what there is to be found on PyPI.

    There are the packages:

    • ordered-set (Python based)
    • orderedset (Cython based)
    • collections-extended
    • boltons (under iterutils.IndexedSet, Python-based)
    • oset (last updated in 2012)

    Some of these implementations are based on the recipe posted by Raymond Hettinger to ActiveState which is also mentioned in other answers here.

    Some differences

    • ordered-set (version 1.1)
    • advantage: O(1) for lookups by index (e.g. my_set[5])
    • oset (version 0.1.3)
    • advantage: O(1) for remove(item)
    • disadvantage: apparently O(n) for lookups by index

    Both implementations have O(1) for add(item) and __contains__(item) (item in my_set).

提交回复
热议问题