Converting a list to a set changes element order

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

    In case you have a small number of elements in your two initial lists on which you want to do set difference operation, instead of using collections.OrderedDict which complicates the implementation and makes it less readable, you can use:

    # initial lists on which you want to do set difference
    >>> nums = [1,2,2,3,3,4,4,5]
    >>> evens = [2,4,4,6]
    >>> evens_set = set(evens)
    >>> result = []
    >>> for n in nums:
    ...   if not n in evens_set and not n in result:
    ...     result.append(n)
    ... 
    >>> result
    [1, 3, 5]
    
    

    Its time complexity is not that good but it is neat and easy to read.

提交回复
热议问题