我有一个如下所示的列表:
[1, 2, 3, 4, 3, 2]
我想删除所有有重复项的项目,所以我得到这样的内容:
[1, 4]
因为2和3有重复。我知道套装,但它们没有实现我想要的。有没有简短有效的方法来做到这一点?
答案 0 :(得分:1)
短:
filtered_list = [x for x in your_list if your_list.count(x) == 1]
有效(适用于大型列表):
counters = dict.fromkeys(your_list, 0)
for item in your_list:
counters[item] += 1
filtered_list = [x for x in your_list if counters[x] == 1]
答案 1 :(得分:0)
使用counter
from collections import Counter
myList = [1, 2, 3, 4, 3, 2]
def getUnique(myList):
cnt = Counter()
for item in myList:
cnt[item] += 1
return [i for i in cnt if cnt[i] < 2]
print getUnique(myList)
答案 2 :(得分:0)
你可以这样做:
import collections
a = [1, 2, 3, 4, 3, 2]
remove = [item for item, count in collections.Counter(a).items() if count > 1]
print([x for x in a if x not in remove])
输出:[1,4]