2013-02-22 57 views
1

如何刪除列表中的項目,如果它在另一個列表中,同時保持重複?從列表中刪除項目,如果它在另一個列表中,同時保持重複 - Python

我已經成功做到這一點,但有沒有更快的方法?

x = [1,2,3,4,7,7,5,6,7,8,8] 
y = [1,4,5,6,8,9] 
z = [] 
for i in x: 
    if i not in y: 
    z.append(i) 
print z 

正確的輸出:

[2, 3, 7, 7, 7] 

另外,列表理解也適用,但這些的唯一途徑?

x = [1,2,3,4,7,7,5,6,7,8,8] 
y = [1,4,5,6,8,9] 
z = [i for i in x if not in y] 

雖然使用集是快了很多,但它不保留重複:

x = [1,2,3,4,7,7,5,6,7,8,8] 
y = [1,4,5,6,8,9] 
print list(set(x) - set(y)) 

設定減法給那失去重複輸出:

[2, 3, 7] 
+0

你可以爲'y'使用一套。 – sloth 2013-02-22 11:03:00

+1

Dominic意味着你可以把'set_y = set(y)'放在列表理解之外,所以你不要一遍又一遍地創建集合。 – 2013-02-22 11:06:21

+1

還有'itertools.ifilterfalse(set(y).__ contains__,x)''。它應該相當快。 – Blender 2013-02-22 11:06:23

回答

2

如果爲了不重要

>>> x = [1,2,3,4,7,7,5,6,7,8,8] 
>>> y = [1,4,5,6,8,9] 
>>> from collections import Counter 
>>> count=Counter(x) 
>>> for i in y: 
...  del count[i] 
... 
>>> list(count.elements()) 
[2, 3, 7, 7, 7] 
相關問題