Python equivalent to java.util.SortedSet?

前端 未结 7 1814
灰色年华
灰色年华 2021-02-05 06:59

Does anybody know if Python has an equivalent to Java\'s SortedSet interface?

Heres what I\'m looking for: lets say I have an object of type foo, and I know

7条回答
  •  一向
    一向 (楼主)
    2021-02-05 07:15

    You can use insort from the bisect module to insert new elements efficiently in an already sorted list:

    from bisect import insort
    
    items = [1,5,7,9]
    insort(items, 3)
    insort(items, 10)
    
    print items # -> [1, 3, 5, 7, 9, 10]
    

    Note that this does not directly correspond to SortedSet, because it uses a list. If you insert the same item more than once you will have duplicates in the list.

提交回复
热议问题