2015-04-01 72 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