如何从一个列表中减去另一个列表?
我想要找出列表 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]
16 个回答
47
如果你遇到重复和排序的问题,可以使用下面这段代码:
[i for i in a if not i in b or b.remove(i)]
a = [1,2,3,3,3,3,4]
b = [1,3]
result: [2, 3, 3, 3, 4]
370
511
使用列表推导式来计算差集,同时保持原始的顺序,参考x
:
[item for item in x if item not in y]
如果你不需要列表的特性(比如顺序),可以使用集合差集,就像其他回答所建议的那样:
list(set(x) - set(y))
为了让x - y
这种写法更方便,可以在一个继承自list
的类中重写__sub__
:
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