[英]'dict' object has no attribute '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
为什么我会收到此错误,我该如何解决?
has_key
已在 Python 3 中删除。从文档中:
- 删除了
dict.has_key()
– 改用in
操作符。
下面是一个例子:
if start not in graph:
return None
在python3中, has_key(key)
被替换为__contains__(key)
在python3.7中测试:
a = {'a':1, 'b':2, 'c':3}
print(a.__contains__('a'))
has_key在Python 3.0 中已被弃用。 或者,您可以使用“in”
graph={'A':['B','C'],
'B':['C','D']}
print('A' in graph)
>> True
print('E' in graph)
>> False
我认为in
确定密钥是否已经存在时使用它被认为是“更pythonic”,如
if start not in graph:
return None
文档中的整个代码将是:
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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.