Converting a list to a set changes element order

后端 未结 11 1087
攒了一身酷
攒了一身酷 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:05

    It's interesting that people always use 'real world problem' to make joke on the definition in theoretical science.

    If set has order, you first need to figure out the following problems. If your list has duplicate elements, what should the order be when you turn it into a set? What is the order if we union two sets? What is the order if we intersect two sets with different order on the same elements?

    Plus, set is much faster in searching for a particular key which is very good in sets operation (and that's why you need a set, but not list).

    If you really care about the index, just keep it as a list. If you still want to do set operation on the elements in many lists, the simplest way is creating a dictionary for each list with the same keys in the set along with a value of list containing all the index of the key in the original list.

    def indx_dic(l):
        dic = {}
        for i in range(len(l)):
            if l[i] in dic:
                dic.get(l[i]).append(i)
            else:
                dic[l[i]] = [i]
        return(dic)
    
    a = [1,2,3,4,5,1,3,2]
    set_a  = set(a)
    dic_a = indx_dic(a)
    
    print(dic_a)
    # {1: [0, 5], 2: [1, 7], 3: [2, 6], 4: [3], 5: [4]}
    print(set_a)
    # {1, 2, 3, 4, 5}
    

提交回复
热议问题