Skip to main content
 首页 » 编程设计

python之如何按值从集合中删除对象

2024年08月14日43sxdcgaq8080

我有一组 Point 对象,我希望能够从我的集合中删除这些对象。然而,Python 似乎是通过指针而不是值来比较它们,所以我不能轻易删除元素,因为它们没有相同的指针,因为它们不是完全相同的对象。这只是对象的问题,而不是基元的问题。

我的问题的一个简化示例:

class Point(): 
    def __init__(self, x, y): 
        self.x = x 
        self.y = y 
 
a = set() 
a.add(Point(0, 0)) 
b = Point(0, 0) 
a.remove(b) 

运行时返回

Traceback (most recent call last): 
  File "example.py", line 9, in <module> 
    a.remove(b) 
KeyError: <__main__.Point object at 0x7f6292376128> 

(显然,特定指针在每次运行时都会发生变化)。

我更喜欢元素 (0, 0)从 a 中删除, 离开 a为空集。

请您参考如下方法:

如果您告诉 Python 如何比较这些对象,它就可以工作。添加两个方法,例如:

代码:

def __eq__(self, other): 
    return self.x == other.x and self.y == other.y 
 
def __hash__(self): 
    return hash((self.x, self.y)) 

测试代码:

class Point(): 
    def __init__(self, x, y): 
        self.x = x 
        self.y = y 
 
    def __eq__(self, other): 
        return self.x == other.x and self.y == other.y 
 
    def __hash__(self): 
        return hash((self.x, self.y)) 
 
 
a = set() 
a.add(Point(0, 0)) 
b = Point(0, 0) 
a.remove(b)