Converting a list to a set changes element order

后端 未结 11 1132
攒了一身酷
攒了一身酷 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-22 00:17

    As denoted in other answers, sets are data structures (and mathematical concepts) that do not preserve the element order -

    However, by using a combination of sets and dictionaries, it is possible that you can achieve wathever you want - try using these snippets:

    # save the element order in a dict:
    x_dict = dict(x,y for y, x in enumerate(my_list) )
    x_set = set(my_list)
    #perform desired set operations
    ...
    #retrieve ordered list from the set:
    new_list = [None] * len(new_set)
    for element in new_set:
       new_list[x_dict[element]] = element
    

提交回复
热议问题