1

如果它在另一个列表中,如何从列表中删除项目,同时保留重复项?

我已经成功了,但是有没有更快的方法?

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]

虽然使用 set 要快得多,但它不会保留重复项:

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]
4

1 回答 1

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]
于 2013-02-22T11:02:19.400 回答