gpt4 book ai didi

python - 在 python 2.7 中搜索重复值列表

转载 作者:太空宇宙 更新时间:2023-11-04 08:44:34 25 4
gpt4 key购买 nike

list1 = ["green","red","yellow","purple","Green","blue","blue"]

所以我得到了一个列表,我想循环遍历列表,看看颜色是否没有被多次提及。如果有,则不会附加到新列表。

所以你应该留下

list2 = ["red","yellow","purple"]

我试过了

list1 = ["green","red","yellow","purple","Green","blue","blue","yellow"]
list2 =[]
num = 0
for i in list1:
if (list1[num]).lower == (list1[i]).lower:
num +=1
else:
list2.append(i)
num +=1

但是我总是报错

最佳答案

使用计数器:https://docs.python.org/2/library/collections.html#collections.Counter .

from collections import Counter
list1 = ["green","red","yellow","purple","green","blue","blue","yellow"]
list1_counter = Counter([x.lower() for x in list1])
list2 = [x for x in list1 if list1_counter[x.lower()] == 1]

请注意,您的示例是错误的,因为 yellow 出现了两次。

关于python - 在 python 2.7 中搜索重复值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41862433/

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