我想取列表x和y的差值:
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [1, 3, 5, 7, 9]
>>> x - y
# should return [0, 2, 4, 6, 8]
我想取列表x和y的差值:
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [1, 3, 5, 7, 9]
>>> x - y
# should return [0, 2, 4, 6, 8]
当前回答
list1 = ['a', 'c', 'a', 'b', 'k']
list2 = ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'd', 'e', 'f']
for e in list1:
try:
list2.remove(e)
except ValueError:
print(f'{e} not in list')
list2
# ['a', 'a', 'c', 'd', 'e', 'f']
这将改变list2。如果你想保护list2,只需复制它,并在这段代码中使用list2的副本。
其他回答
如果列表允许重复元素,你可以使用Counter from collections:
from collections import Counter
result = list((Counter(x)-Counter(y)).elements())
如果你需要保留x中元素的顺序:
result = [ v for c in [Counter(y)] for v in x if not c[v] or c.subtract([v]) ]
def listsubtraction(parent,child):
answer=[]
for element in parent:
if element not in child:
answer.append(element)
return answer
我认为这应该可行。我是初学者,所以请原谅我的错误
在set中查找值比在list中查找值更快:
[item for item in x if item not in set(y)]
我相信这将会比:
[item for item in x if item not in y]
两者都保持了列表的顺序。
这是一个“集合减法”操作。使用设定的数据结构。
在Python 2.7中:
x = {1,2,3,4,5,6,7,8,9,0}
y = {1,3,5,7,9}
print x - y
输出:
>>> print x - y
set([0, 8, 2, 4, 6])
我们也可以使用set方法来查找两个列表之间的差异
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
y = [1, 3, 5, 7, 9]
list(set(x).difference(y))
[0, 2, 4, 6, 8]