Does Python have an ordered set?

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

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

14条回答
  •  你的背包
    2020-11-21 13:42

    As others have said, OrderedDict is a superset of an ordered set in terms of functionality, but if you need a set for interacting with an API and don't need it to be mutable, OrderedDict.keys() is actually an implementation abc.collections.Set:

    import random
    from collections import OrderedDict, abc
    
    a = list(range(0, 100))
    random.shuffle(a)
    
    # True
    a == list(OrderedDict((i, 0) for i in a).keys())
    
    # True
    isinstance(OrderedDict().keys(), abc.Set)   
    

    The caveats are immutability and having to build up the set like a dict, but it's simple and only uses built-ins.

提交回复
热议问题