在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 :(得分:127)
has_key
。来自documentation:
- 已删除
dict.has_key()
- 请改用in
运算符。
以下是一个例子:
if start not in graph:
return None
答案 1 :(得分:6)
has_key 在 Python 3.0 中已被弃用。 或者,您可以使用'in'
graph={'A':['B','C'],
'B':['C','D']}
print('A' in graph)
>> True
print('E' in graph)
>> False
答案 2 :(得分:5)
我认为在确定某个密钥是否已存在时,仅使用in
会被视为“更加pythonic”,如
if start not in graph:
return None
答案 3 :(得分:4)
答案 4 :(得分:3)
文件中的整个代码将是:
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(graph,'A','D')
您应该在IDLE中收到的答案是
['A', 'B', 'C', 'D']
答案 5 :(得分:0)
在python3中,has_key(key)
被__contains__(key)
取代
在python3.7中测试过:
a = {'a':1, 'b':2, 'c':3}
print(a.__contains__('a'))