Skip to main content
 首页 » 编程设计

python之从列表中删除所有重复项之不保留重复项的实例

2025年05月04日15jyk

我有一个列表:

myList = [-3, -3, 6, 10, 10, 16, 16, 40, 40, 60, 60, 100, 100, 140, 140, 211, -8] 

我怎样才能有效地从中删除所有重复的项目,即有一个像这样的新列表:

[6,211,-8] 

我知道一种方法,通过跟踪重复项,然后使用 python set() 删除它们,即

listOfDuplicates = [x for x, y in collections.Counter(myList).items() if y > 1] 
newList = list(set(myList) - set(listOfDuplicates)) 

在 python 中是否有更好的方法(保留顺序)?

请您参考如下方法:

最好的方法是反转条件,如suggested by Jonathon Reinhart

import collections 
print [x for x, y in collections.Counter(myList).iteritems() if y == 1] 
# [6, 211, -8] 

注意:此方法将无法维护元素的顺序。例如,当

myList = [1, 1000, 10] 

结果是

[1000, 1, 10] 

因为 collections.Counter 在内部只是一个字典。由于字典使用散列,因此无法保证顺序。

为了保护订单,你可以这样做,如suggested by DSM

c = Counter(myList) 
print [x for x in myList if c[x] == 1]