如果项目位于另一个列表中,则从列表中删除项目,同时保留副本 - Python

时间:2013-02-22 10:59:09

标签: python list set list-comprehension list-comparison

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

我已经成功做到了这一点,但有更快的方法吗?

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))

set subtraction给出了丢失副本的输出:

[2, 3, 7]

1 个答案:

答案 0 :(得分: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]
相关问题