【问题标题】:Getting the key of a dictionary from its hash in python?从python中的哈希中获取字典的键?
【发布时间】:2014-01-03 01:01:48
【问题描述】:

我有一个使用邻接列表来跟踪顶点和边的图类,以及一个带有预定义散列函数的顶点类,如下所示:

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

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

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

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

【问题讨论】:

    标签: python object dictionary hash graph


    【解决方案1】:

    只需使用会员测试:

    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
    

    【讨论】:

    • 另外,Vertex 后面的括号是多余的。 :P
    • 当然可以,但我会尝试呼应 OP 使用的风格,而这种风格并不重要。
    猜你喜欢
    • 2012-08-17
    • 2017-08-04
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    • 2014-09-14
    • 2014-01-30
    • 1970-01-01
    • 2018-05-29
    相关资源
    最近更新 更多