Converting a list to a set changes element order

后端 未结 11 1399
攒了一身酷
攒了一身酷 2020-11-21 23:26

Recently I noticed that when I am converting a list to set the order of elements is changed and is sorted by character.

Consider this examp

11条回答
  •  情深已故
    2020-11-21 23:55

    Building on Sven's answer, I found using collections.OrderedDict like so helped me accomplish what you want plus allow me to add more items to the dict:

    import collections
    
    x=[1,2,20,6,210]
    z=collections.OrderedDict.fromkeys(x)
    z
    OrderedDict([(1, None), (2, None), (20, None), (6, None), (210, None)])
    

    If you want to add items but still treat it like a set you can just do:

    z['nextitem']=None
    

    And you can perform an operation like z.keys() on the dict and get the set:

    z.keys()
    [1, 2, 20, 6, 210]
    

提交回复
热议问题