慕田峪9158850
2019-08-30 16:46:37
我想做類似的事情:>>> 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列表不支持這種做法最好的方法是什么?
3 回答

qq_笑_17
TA貢獻(xiàn)1818條經(jīng)驗 獲得超7個贊
使用列表理解:
[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
但是如果你不是絕對需要列表屬性(例如,排序),只需使用集合作為其他答案推薦。

紫衣仙女
TA貢獻(xiàn)1839條經(jīng)驗 獲得超15個贊
這是一個“集合減法”操作。使用set數(shù)據(jù)結(jié)構(gòu)。
在Python 2.7中:
x = {1,2,3,4,5,6,7,8,9,0}
y = {1,3,5,7,9}
print x - y
輸出:
>>> print x - y
set([0, 8, 2, 4, 6])
添加回答
舉報
0/150
提交
取消