如何使用此功能从列表中删除重复项?

问题描述 投票:0回答:2

我是python的新手。有人可以帮我理解为什么以下功能不起作用吗?应该返回一个删除了重复项的新列表,而是打印[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并将其删除,后5个计数为2并删除,而第5个5将计数为1并附加到解决方案列表中。我无法确定为什么5s将被完全删除,而4s无法被删除。

python python-3.x list syntax
2个回答
0
投票

您现在不能迭代从列表中删除项目。通过内部增加索引来进行迭代。

如果要保留一个项目的最后一次出现,最好先将它们数一数:

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

0
投票

使用python中的set数据类型来删除重复项。

a = [4,5,5,5,4,6]
solution = list(set(a))

输出:

[4,5,6]

0
投票

您在遍历列表时更改列表,这是一个大错误。当您删除第一个4时,然后第二个4仍然是单个项目并且不会被删除。当您删除4时,您还会跳过前5个,而第二个和第三个5不是单个项目,因此它们将被删除,而从不将5添加到解决方案中。

def remove_duplicates(l):
    solution = []
    for item in l: # if you don't care about order you can do for item in set(l)
        if l.count(item) < 2:
            solution.append(item)
    return solution


print (remove_duplicates([4,5,5,5,4,6]))
© www.soinside.com 2019 - 2024. All rights reserved.