问题:’dict’对象没有属性’has_key’
在Python中遍历图形时,我收到此错误:
‘dict’对象没有属性’has_key’
这是我的代码:
def find_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if not graph.has_key(start):
        return None
    for node in graph[start]:
        if node not in path:
            newpath = find_path(graph, node, end, path)
            if newpath: return newpath
    return None
该代码旨在查找从一个节点到另一节点的路径。代码源:http : //cs.mwsu.edu/~terry/courses/4883/lectures/graphs.html
为什么会出现此错误,我该如何解决?
回答 0
回答 1
has_key在Python 3.0中已被弃用。或者,您可以使用“ in”
graph={'A':['B','C'],
   'B':['C','D']}
print('A' in graph)
>> True
print('E' in graph)
>> False
回答 2
在python3中,has_key(key)被替换为__contains__(key)
在python3.7中测试:
a = {'a':1, 'b':2, 'c':3}
print(a.__contains__('a'))
回答 3
我认为,仅in在确定某个键是否已存在时才使用它,它被认为是“更多的pythonic” ,如
if start not in graph:
    return None
回答 4
该文档中的整个代码将为:
graph = {'A': ['B', 'C'],
             'B': ['C', 'D'],
             'C': ['D'],
             'D': ['C'],
             'E': ['F'],
             'F': ['C']}
def find_path(graph, start, end, path=[]):
        path = path + [start]
        if start == end:
            return path
        if start not in graph:
            return None
        for node in graph[start]:
            if node not in path:
                newpath = find_path(graph, node, end, path)
                if newpath: return newpath
        return None
写入后,保存文档并按F 5
之后,您将在Python IDLE shell中运行的代码为:
find_path(图,’A’,’D’)
您应该在“ IDLE”中收到的答案是
['A', 'B', 'C', 'D'] 
回答 5
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
