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