Skip to main content
 首页 » 编程设计

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

2025年05月04日25shanyou

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 出现了两次。