Python列表减法操作 [英] Python list subtraction operation

查看:99
本文介绍了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列表不支持此功能 最好的方法是什么?

But this is not supported by python lists What is the best way of doing it?

推荐答案

使用列表理解:

[item for item in x if item not in y]

如果要使用-中缀语法,则可以执行以下操作:

If you want to use the - infix syntax, you can just do:

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])

然后您可以像这样使用它:

you can then use it like:

x = MyList(1, 2, 3, 4)
y = MyList(2, 5, 2)
z = x - y   

但是,如果您并非绝对需要列表属性(例如,订购),则只需将集用作其他答案即可.

But if you don't absolutely need list properties (for example, ordering), just use sets as the other answers recommend.

这篇关于Python列表减法操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆