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

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

问题描述

我在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?

推荐答案

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'll need to use set([1, 2]).symmetric_difference(set([2, 3])).

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

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