当前位置: 代码迷 >> python >> python从另外两个列表创建一个列表
  详细解决方案

python从另外两个列表创建一个列表

热度:38   发布时间:2023-07-16 09:56:30.0

我是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  

使用set s:

>>> set(list2) - set(list1)
{'orange', 'pink'}

尝试使用集合:

>>> list(set(list2) - set(list1))
['orange', 'pink']

您可以使用python集( ):

s1 = set(list1)
s2 = set(list2)
list(s2.difference(s1))

比您想象的要简单一些

newlist = []

for color in list2:
   if color not in list1:
        newlist.append(color2)

return newlist

list1转换为集合将使其更有效