我想做类似的事情:
>>> x = [1,2,3,4,5,6,7,8,9,0]
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> y = [1,3,5,7,9]
>>> y
[1, 3, 5, 7, 9]
>>> y - x # (should return [2,4,6,8,0])
但python列表不支持这一点
我想做类似的事情:
>>> x = [1,2,3,4,5,6,7,8,9,0]
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> y = [1,3,5,7,9]
>>> y
[1, 3, 5, 7, 9]
>>> y - x # (should return [2,4,6,8,0])
但python列表不支持这一点
使用列表理解:
[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
但是,如果你不一定需要列表属性(例如,排序),那么就按照其他答案的建议使用集合.