繁体   English   中英

有没有办法按值删除列表中的对象?

[英]Is there a way to delete an object in list by value?

'list.remove'函数不按值比较对象

假设代码是:

class item:
def __init__(self, a, b):
    self.feild1 = a
    self.field2 = b

a = item(1,4)
b = item(1,4)
l = [a]
l.remove(b) # doesn't remove l[0]

因为您没有提供__eq__实现,所以您的类从object继承该方法。 object.__eq__不比较属性的值,它只是检查id(a) == id(b) 你需要编写自己的__eq__

class item:
    def __init__(self, a, b):
        self.field1 = a
        self.field2 = b
    def __eq__(self, other):
        if not isinstance(other, item):
            return NotImplemented
        return self.field1 == other.field1 and self.field2 == other.field2

a = item(1,4)
b = item(1,4)
l = [a]
l.remove(b)

print(l)
# []

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM