2015-04-01 71 views
1

消除常见的元素,如果我有两个列表:Python的 - 从两个列表

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

我如何得到

a - b = [1,2,4] 

使得从B中的一个元素只删除一个元素从,如果该元素存在于a。

回答

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)] 
+0

我碰到下面的错误 - 导入错误:无法导入名称“izip_longest” – hmm 2015-04-01 10:48:50

+0

@hmm对不起,你是在Python 3,你需要'zip_longest' fised! – Kasramvd 2015-04-01 10:53:17

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

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

+0

该代码找到常见元素,我的不好。 – satikin 2015-04-01 11:05:18

+0

你可以做'set(a) - set(b)',但是这也会删除所有重复项,并加扰可能不打算的顺序。 – 2015-04-01 11:35:53