Python 从列表中删除副本和原件

Python 从列表中删除副本和原件,python,list,duplicates,Python,List,Duplicates,给定一个字符串列表,我想删除重复项和原始单词 例如: lst = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e'] 输出应删除重复项, 所以像这样的['a','b','d'] 我不需要保留顺序。您可以创建第二个空列表,并且只附加不在其中的项目 oldList = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e'] newList = [] for item in oldList: if item not in newList

给定一个字符串列表,我想删除重复项和原始单词

例如:

lst = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
输出应删除重复项, 所以像这样的
['a','b','d']


我不需要保留顺序。

您可以创建第二个空列表,并且只附加不在其中的项目

oldList = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
newList = []
for item in oldList:
    if item not in newList:
        newList.append(item)
print newList
我没有带解释器,但逻辑似乎很合理。

使用a,然后只保留那些计数为1的值:

t = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
print [a for a in t if t.count(a) == 1]
from collections import counter

[k for k, v in Counter(lst).items() if v == 1]
这是一个O(N)算法;您只需要在N个项目的列表中循环一次,然后在较少的项目( 如果顺序很重要,并且您正在使用Python<3.6,请将以下步骤分开:

counts = Counter(lst)
[k for k in lst if counts[k] == 1]
演示:

两种方法的顺序相同是巧合;对于Python 3.6之前的Python版本,其他输入可能会导致不同的顺序

在Python3.6中,字典的实现发生了变化,现在保留了输入顺序

lst = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
from collections import Counter
c = Counter(lst)
print([k for k,v in c.items() if v == 1 ])

将对每个元素的出现次数进行计数,如果v==1,我们将使用
保留
计数/值为==1的元素

如果您的列表是:

lst = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
然后

将返回以下内容:

['a', 'c', 'b', 'e', 'd']
这不是adhankar想要的

完全过滤所有重复项可以通过列表理解轻松完成:

[item for item in lst if lst.count(item) == 1]
其结果将是:

['a', 'b', 'd']
item代表列表lst中的每个项,但只有当lst.count(item)等于1时,它才会附加到新列表中,这确保了该项在原始列表lst中只存在一次


查阅列表理解了解更多信息:

这也给了我['a','b','c','d','e'],我需要输出为['a','b','d']你的算法是平方真的吗?带if的python列表理解是否具有二次时间复杂度?你能解释一下吗?你的算法的时间复杂度是多少?你认为lst.count(item)在做什么?你的解决方案的复杂度是多少?它是一个
O(n)
算法
[item for item in lst if lst.count(item) == 1]
['a', 'b', 'd']