获取两个列表之间的差异 [英] Get difference between two lists

查看:24
本文介绍了获取两个列表之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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])).

这篇关于获取两个列表之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆