Converting a list to a set changes element order

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

    In Python 3.6, set() now should keep the order, but there is another solution for Python 2 and 3:

    >>> x = [1, 2, 20, 6, 210]
    >>> sorted(set(x), key=x.index)
    [1, 2, 20, 6, 210]
    

提交回复
热议问题