我想做一些类似的事情:
>>> 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列表并不支持这一点,最好的方法是什么?
发布于 2010-08-07 08:19:08
使用列表理解:
[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
但是,如果您不是绝对需要列表属性(例如,排序),则只需按照其他答案建议的方式使用集合。
发布于 2010-08-07 07:45:35
发布于 2013-11-28 14:49:44
如果重复和排序项目有问题:
[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]
https://stackoverflow.com/questions/3428536
复制相似问题