![](/img/trans.png)
[英]How to remove duplicates from a list of custom objects in Python using a custom equality function?
[英]How to remove duplicates from a list using this function?
我是 python 的新手。 有人可以帮我理解为什么下面的 function 不起作用吗? 它应该返回一个删除重复项的新列表,而是打印[4,6]
。
def remove_duplicates(l):
solution = []
for item in l:
if l.count(item) < 2:
solution.append(item)
else:
l.remove(item)
return solution
print (remove_duplicates([4,5,5,5,4,6]))
我认为它在列表中一次迭代一个项目。 因此,前 5 个的计数为 3 并被删除,后五个的计数为 2 并被删除,第三个 5 的计数为 1 并附加到解决方案列表中。 我无法理解为什么 5s 会被完全移除而 4s 不会。
使用 python 中的设置数据类型来删除重复项。
a = [4,5,5,5,4,6]
solution = list(set(a))
Output:
[4,5,6]
您不能从列表中删除项目,您目前正在迭代。 迭代是通过在内部增加索引来完成的。
如果您想保留一个项目的最后一次出现,最好首先计算它们:
from collections import Counter
def remove_duplicates(l):
solution = []
counts = Counter(l)
for item in l:
if counts[item] == 1:
solution.append(item)
else:
counts[item] -= 1
return solution
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.