Python “set” with duplicate/repeated elements

后端 未结 8 1864
栀梦
栀梦 2020-12-28 12:52

Is there a standard way to represent a \"set\" that can contain duplicate elements.

As I understand it, a set has exactly one or zero of an element. I want functiona

相关标签:
8条回答
  • 2020-12-28 13:16

    If you need duplicates, use a list, and transform it to a set when you need operate as a set.

    0 讨论(0)
  • 2020-12-28 13:17

    An alternative Python multiset implementation uses a sorted list data structure. There are a couple implementations on PyPI. One option is the sortedcontainers module which implements a SortedList data type that efficiently implements set-like methods like add, remove, and contains. The sortedcontainers module is implemented in pure-Python, fast-as-C implementations (even faster), has 100% unit test coverage, and hours of stress testing.

    Installation is easy from PyPI:

    pip install sortedcontainers
    

    If you can't pip install then simply pull the sortedlist.py file down from the open-source repository.

    Use it as you would a set:

    from sortedcontainers import SortedList
    survey = SortedList(['blue', 'red', 'blue', 'green']]
    survey.add('blue')
    print survey.count('blue') # "3"
    survey.remove('blue')
    

    The sortedcontainers module also maintains a performance comparison with other popular implementations.

    0 讨论(0)
提交回复
热议问题