我想要这样的东西:
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> y = [1, 3, 5, 7, 9]
>>> y - x
# should return [2,4,6,8,0]
最佳答案
使用列表推导:
[item for item in x if item not in y]
如果你想使用 -
中缀语法,你可以这样做:
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
但是,如果您绝对不需要列表属性(例如,排序),只需按照其他答案的建议使用集合。
关于Python列表减法运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3428536/