Python列表减法操作

2024-03-29 00:00:28 发布

您现在位置: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列表不支持这个 最好的方法是什么?


Tags: 方法列表return事情should
3条回答

这是一个“集合减法”运算。使用set数据结构。

在Python2.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])

使用列表理解:

[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   

但如果您不完全需要列表属性(例如,排序),只需使用其他答案推荐的集合。

使用set difference

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

或者你可以只设置x和y,这样你就不需要做任何转换。

相关问题 更多 >