Python - 从两个列表中删除常见元素

时间:2015-04-01 10:38:13

标签: python-3.x

如果我有两个清单:

a = [1,2,1,2,4] and b = [1,2,4]

我如何获得

a - b = [1,2,4]

这样b中的一个元素只从a中删除一个元素。如果该元素存在于。

2 个答案:

答案 0 :(得分:1)

您可以使用itertools.zip_longest压缩不同长度的列表,然后使用列表理解:

>>> from itertools import zip_longest
>>> [i for i,j in izip_longest(a,b) if i!=j]
[1, 2, 4]

演示:

>>> list(izip_longest(a,b))
[(1, 1), (2, 2), (1, 4), (2, None), (4, None)]

答案 1 :(得分:0)

a = [1,2,1,2,4] 
b = [1,2,4]
c= set(a) & set(b)
d=list(c)

答案只是对这个主题的一点修改答案: Find non-common elements in lists

因为你不能迭代一个set对象: https://www.daniweb.com/software-development/python/threads/462906/typeerror-set-object-does-not-support-indexing

相关问题