从列表中删除项目,如果它在另一个列表中,同时保持重复 - Python
问题描述:
如何删除列表中的项目,如果它在另一个列表中,同时保持重复?从列表中删除项目,如果它在另一个列表中,同时保持重复 - 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]
答
如果为了不重要
>>> 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]
你可以为'y'使用一套。 – sloth 2013-02-22 11:03:00
Dominic意味着你可以把'set_y = set(y)'放在列表理解之外,所以你不要一遍又一遍地创建集合。 – 2013-02-22 11:06:21
还有'itertools.ifilterfalse(set(y).__ contains__,x)''。它应该相当快。 – Blender 2013-02-22 11:06:23