问题描述
我是python的初学者,我尝试编写一个包含两个列表的函数,对于第一个列表中的每个项目,查找第二个列表,并将第一个列表中的每个项目与第二个列表中的每个项目进行比较。 它需要返回一个新列表,其中包含未出现在第一个列表中的所有项目。
例如,给定一个列表:
list1 = ['yellow', 'blue', 'green']
第二个列表:
list2 = ['orange', 'green', 'blue', 'pink', 'yellow']
它应仅返回list2中不在list1中的项目的列表,如下所示:
['orange', 'pink']
我编写了许多函数,但是它们不断返回重复项,对此我真的非常感谢!
def different_colors(list1, list2):
newlist = []
for color in list1:
newlist = []
for color2 in list2:
if color1 != color2:
newlist.append(color2)
return newlist
1楼
使用set
s:
>>> set(list2) - set(list1)
{'orange', 'pink'}
2楼
尝试使用集合:
>>> list(set(list2) - set(list1))
['orange', 'pink']
3楼
您可以使用python集( ):
s1 = set(list1)
s2 = set(list2)
list(s2.difference(s1))
4楼
比您想象的要简单一些
newlist = []
for color in list2:
if color not in list1:
newlist.append(color2)
return newlist
将list1
转换为集合将使其更有效