如何从一个列表中减去另一个列表?

380 投票
16 回答
681729 浏览
提问于 2025-04-16 02:27

我想要找出列表 xy 之间的 差异

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

使用 集合差集

>>> z = list(set(x) - set(y))
>>> z
[0, 8, 2, 4, 6]

或者,你可以直接把 x 和 y 定义为集合,这样就不需要进行任何转换了。

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   

撰写回答