我知道这个问题已经被问过很多次了,但我不是在问如何只从列表中删除重复的元素,我还想删除重复的元素。
例如,如果我有一个列表:
x = [1, 2, 5, 3, 4, 1, 5]
我希望列表是:
x = [2, 3, 4] # removed 1 and 5 since they were repeated
我不能使用 set
,因为它将包括 1
和 5
。
我应该使用计数器
吗?有没有更好的办法?
最佳答案
这应该用 Counter 来完成目的。这是微不足道的。
from collections import Counter
x = [k for k, v in Counter([1, 2, 5, 3, 4, 1, 5]).iteritems() if v == 1]
print x
输出:
[2, 3, 4]
关于python - 从列表和元素本身中删除重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5245872/