source=[1,2,3,4,2,3,5,6]
dst=[]
for item in source:
if item not in dst:
dst.append(item)
print(dst) # [1,2,3,4,5,6]
我可以将代码简化为以下内容:
dst=[item for item in [1,2,3,4,2,3,5,6] if item not in 'this array']
谢谢
一个集合可能就是您正在寻找的集合,因为您在创建它时无法引用该数组:
>>> source = [1,2,3,4,2,3,5,6]
>>> set(source)
{1, 2, 3, 4, 5, 6}
但是,如果您确实希望保留原始订单,则可以使用集合(dst
)跟踪已添加到seen
的内容:
>>> source = [1,2,3,4,2,3,5,6]
>>> seen = set()
>>> dst = []
>>> for i in source:
>>> if i not in seen:
>>> dst.append(i)
>>> seen.add(i)
>>>
>>> dst
[1, 2, 3, 4, 5, 6]
你不能从列表理解中引用dst
,但你可以通过在每次迭代中对它进行切片来检查source
中先前迭代的项目的当前项:
source = [1, 2, 3, 4, 2, 3, 5, 6]
dst = [item for i, item in enumerate(source)
if item not in source[0:i]]
print(dst) # [1, 2, 3, 4, 5, 6]
如果使用if和for是你的要求怎么样?
[dst.append(item) for item in source if item not in dst]
好吧,您可以使用列表推导修改现有列表,而不是创建新列表,如下所示:
In [1]: source
Out[1]: [1, 9, 2, 5, 6, 6, 4, 1, 4, 11]
In [2]: [ source.pop(i) for i in range(len(source))[::-1] if source.count(source[i]) > 1 ]
Out[2]: [4, 1, 6]
In [3]: source
Out[3]: [1, 9, 2, 5, 6, 4, 11]
作为另一种方法,您可以先使用set获取唯一列表,然后根据源索引值对其进行排序,如下所示:
source = [1, 9, 2, 5, 6, 6, 4, 1, 4, 11]
d = list(set(source))
d.sort(key=source.index)
print(d) # [1, 9, 2, 5, 6, 4, 11]