gpt4 book ai didi

python - 如果项目出现不止一次,则删除列表中所有出现的项目

转载 作者:行者123 更新时间:2023-12-05 08:52:32 24 4
gpt4 key购买 nike

我需要帮助解决一个编码挑战,该挑战要求删除列表中多次出现的所有项目。我的代码只删除了一次。它不会完全删除项目。

def solution(data, n):
for x in data:
while data.count(x) > 1:
data.remove(x)
continue
print(data)

solution([1, 2, 2, 3, 3, 4, 5, 5], 1)
expected result: [1, 4]
actual restult: [1, 2, 3, 4, 5]

最佳答案

你可以使用collections.Counter计算 data 中每个元素的所有实例,然后根据此计数仅打印相关元素:

from collections import Counter


def solution(data, n):
histogram = Counter(data)
print([d for d in data if histogram[d] <= n])

solution([1, 2, 2, 3, 3, 4, 5, 5], 1)

或者直接使用data.count():

def solution(data, n):
print([d for d in data if data.count(d) <= n])

solution([1, 2, 2, 3, 3, 4, 5, 5], 1)

关于python - 如果项目出现不止一次,则删除列表中所有出现的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56566062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com