获取两个列表之间的差异
问题描述:
我在 Python 中有两个列表,如下所示:
I have two lists in Python, like these:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
我需要创建第三个列表,其中包含第一个列表中第二个列表中不存在的项目.从我必须得到的例子
I need to create a third list with items from the first list which aren't present in the second one. From the example I have to get
temp3 = ['Three', 'Four']
有没有不用循环和检查的快速方法?
Are there any fast ways without cycles and checking?
答
获取在 temp1
中但不在 temp2
中的元素:
To get elements which are in temp1
but not in temp2
:
In [5]: list(set(temp1) - set(temp2))
Out[5]: ['Four', 'Three']
注意它是不对称的:
In [5]: set([1, 2]) - set([2, 3])
Out[5]: set([1])
您可能期望/希望它等于 set([1, 3])
的地方.如果你确实想要 set([1, 3])
作为你的答案,你可以使用 set([1, 2]).symmetric_difference(set([2, 3]))代码>.
where you might expect/want it to equal set([1, 3])
. If you do want set([1, 3])
as your answer, you can use set([1, 2]).symmetric_difference(set([2, 3]))
.