我想取列表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]
当前回答
这是一个“集合减法”操作。使用设定的数据结构。
在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]
如果重复和订购项目是问题:
[i为a中的i,如果不是b中的i或b中的i,删除(i)]
a = [1,2,3,3,3,3,4]
b = [1,3]
result: [2, 3, 3, 3, 4]
试试这个。
def subtract_lists(a, b):
""" Subtracts two lists. Throws ValueError if b contains items not in a """
# Terminate if b is empty, otherwise remove b[0] from a and recurse
return a if len(b) == 0 else [a[:i] + subtract_lists(a[i+1:], b[1:])
for i in [a.index(b[0])]][0]
>>> x = [1,2,3,4,5,6,7,8,9,0]
>>> y = [1,3,5,7,9]
>>> subtract_lists(x,y)
[2, 4, 6, 8, 0]
>>> x = [1,2,3,4,5,6,7,8,9,0,9]
>>> subtract_lists(x,y)
[2, 4, 6, 8, 0, 9] #9 is only deleted once
>>>
在set中查找值比在list中查找值更快:
[item for item in x if item not in set(y)]
我相信这将会比:
[item for item in x if item not in y]
两者都保持了列表的顺序。
@aaronasterling提供的答案看起来不错,但是,它与列表的默认接口不兼容:x = MyList(1,2,3,4) vs x = MyList([1,2,3,4])。因此,下面的代码可以用作更友好的python列表:
class MyList(list):
def __init__(self, *args):
super(MyList, self).__init__(*args)
def __sub__(self, other):
return self.__class__([item for item in self if item not in other])
例子:
x = MyList([1, 2, 3, 4])
y = MyList([2, 5, 2])
z = x - y