Does Python have an ordered set?

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

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

14条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 13:37

    For many purposes simply calling sorted will suffice. For example

    >>> s = set([0, 1, 2, 99, 4, 40, 3, 20, 24, 100, 60])
    >>> sorted(s)
    [0, 1, 2, 3, 4, 20, 24, 40, 60, 99, 100]
    

    If you are going to use this repeatedly, there will be overhead incurred by calling the sorted function so you might want to save the resulting list, as long as you're done changing the set. If you need to maintain unique elements and sorted, I agree with the suggestion of using OrderedDict from collections with an arbitrary value such as None.

提交回复
热议问题