gpt4 book ai didi

Python列表减法运算

转载 作者:IT老高 更新时间:2023-10-28 12:19:10 30 4
gpt4 key购买 nike

我想要这样的东西:

>>> 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com