python从另外两个列表创建一个列表,只包含唯一的项目

时间:2014-03-23 20:09:53

标签: python

我是python的初学者,我正在尝试编写一个包含两个列表的函数, 并且对于第一个列表中的每个项目,查看第二个列表,并比较每个列表 第一个列表中的项目,第二个列表中的每个项目。它需要返回一个包含all的新列表 未出现在第一个列表中的项目。

例如,给出一个列表:

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  

2 个答案:

答案 0 :(得分:1)

使用列表理解:

[k for k in dictionary.keys() if k not in listt]

答案 1 :(得分:1)

我会使用Python集。

>>> list1 = ['yellow', 'blue', 'green']
>>> list2 = ['orange', 'green', 'blue', 'pink', 'yellow']
>>> list(set(list2).difference(set(list1)))
['orange', 'pink']

Python sets是关于操纵独特元素的集合。他们为此目的有特定的方法。

相关问题