'dict' object has no attribute 'has_key'
在python中遍历一个图时,a我接收到这个错误:
'dict' object has no attribute 'has_key'
这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 | 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/schools/graphs.html
为什么我会得到这个错误,我如何修复它?
在python3中删除了
- Removed
dict.has_key() – use thein operator instead.
下面是一个例子:
1 2 | if start not in graph: return None |
python 3.0中的键是否已被弃用?或者,您可以使用"in"
1 2 3 4 5 6 7 8 | graph={'A':['B','C'], 'B':['C','D']} print('A' in graph) >> True print('E' in graph) >> False |
我认为在确定钥匙是否已经存在时,只使用
1 2 | if start not in graph: return None |
文档中的整个代码将是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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空闲shell中运行的代码将是:
找到"路径"(图"A","D")。
你在空闲时应该得到的答案是
1 | ['A', 'B', 'C', 'D'] |