在python中从字典的散列中获取字典的密钥?

2024-06-30 16:26:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个使用邻接列表跟踪顶点和边的graph类,还有一个带有预定义哈希函数的vertex类,如下所示:

class Vertex():
    def __init__(self, name):
         self.name = name
    def __hash__(self):
         return hash(self.name)

本质上,在我的Graph类中,我有一个名为addVertex的方法,它接收一个顶点对象,并在添加它之前检查它是否已经存在于图中。如果它已经存在,我想返回已经在图中的对象,而不是我传递给方法的参数。我将如何着手实施这一点?你知道吗

class Graph():
    def __init__(self):
        self.adjList = {}

    def addVertex(vertex):
        try:
            self.adjList[vertex]
            return ???????????
        except:
            self.adjList[vertex] = {}
            return vertex

Tags: 对象方法nameself列表returninitdef
1条回答
网友
1楼 · 发布于 2024-06-30 16:26:19

只需使用成员资格测试:

if vertex in self.adjList:

dict.__contains__实现将自动使用__hash__特殊方法。你知道吗

请注意,Vertex类还必须实现__eq__相等方法:

class Vertex():
    def __init__(self, name):
         self.name = name
    def __hash__(self):
         return hash(self.name)
    def __eq__(self, other):
         if not isinstance(other, type(self)):
             return NotImplemented
         return self.name == other.name

相关问题 更多 >