最近我注意到,当我转换一个列表来设置元素的顺序是改变的,并按字符排序。

想想这个例子:

x=[1,2,20,6,210]
print(x)
# [1, 2, 20, 6, 210] # the order is same as initial order

set(x)
# set([1, 2, 20, 210, 6]) # in the set(x) output order is sorted

我的问题是

为什么会这样? 如何才能在不丢失初始顺序的情况下进行设置操作(特别是设置差异)?


当前回答

这里有一个简单的方法:

x=[1,2,20,6,210]
print sorted(set(x))

其他回答

上面的最高分概念的实现,将它带回一个列表:

def SetOfListInOrder(incominglist):
    from collections import OrderedDict
    outtemp = OrderedDict()
    for item in incominglist:
        outtemp[item] = None
    return(list(outtemp))

在Python 3.6和Python 2.7上测试(简要)。

迟了,但你可以用熊猫,pd。转换列表,同时保持顺序:

import pandas as pd
x = pd.Series([1, 2, 20, 6, 210, 2, 1])
print(pd.unique(x))

输出: 数组([1,2,20,6,210])

适用于字符串列表

x = pd.Series(['c', 'k', 'q', 'n', 'p','c', 'n'])
print(pd.unique(x))

输出 ['c' 'k' 'q' 'n' 'p']

如果愿意,可以删除重复的值并保持插入的列表顺序

lst = [1,2,1,3]
new_lst = []

for num in lst :
    if num not in new_lst :
        new_lst.append(num)

# new_lst = [1,2,3]

如果你想要的是“order”,不要使用“sets”来删除重复,

使用集合进行搜索。 X在列表中 花费O(n)时间 在哪里 集合中的X 在大多数情况下需要O(1)时间*

在Python 3.6中,set()现在应该保持顺序,但Python 2和3有另一个解决方案:

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

这里有一个简单的方法:

x=[1,2,20,6,210]
print sorted(set(x))