Python列表减法运算

标签 python list

我想要这样的东西:

>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> y = [1, 3, 5, 7, 9]  
>>> y - x
# should return [2,4,6,8,0]

最佳答案

使用列表推导:

[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   

但是,如果您绝对不需要列表属性(例如,排序),只需按照其他答案的建议使用集合。

关于Python列表减法运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3428536/

相关文章:

python - 如何将事件参数传递给运行以响应 Splunk 警报的 Python 脚本?

c++ - 我对 std::list 的实现给出了很多错误

Python 使用另一个列表迭代列表

python - 为什么 append() 在 Python 中总是返回 None?

javascript - API 在 Postman 中有效,但在浏览器中无效

python - 使用 PyPDF2 为 pdf 页面添加边距

python - 列表 2 中的哪些数字大于和小于列表 1 中的每个数字

python - 如何在 Python 中对 Active Directory 服务器进行两阶段身份验证?

python - 如何在 Python 中获取具有最小/最大属性的列表元素?

Python 排序和比较嵌套字典