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

Python 有没有办法按值删除列表中的对象?,python,python-3.x,Python,Python 3.x,“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] 因为您没有提供\uuuuuuueq\uuuuuu实现,所以您的类继承了对象的方法object.\uuuueq\uuuuuu不比较属性的值,它

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

因为您没有提供
\uuuuuuueq\uuuuuu
实现,所以您的类继承了
对象的方法
object.\uuuueq\uuuuuu
不比较属性的值,它只是检查
id(a)==id(b)
。您需要编写自己的
\uuuuu eq\uuuu

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