Ash*_*shi 72 python dictionary python-3.x
在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
Run Code Online (Sandbox Code Playgroud)
该代码旨在找到从一个节点到另一个节点的路径.代码来源:http://cs.mwsu.edu/~terry/courses/4883/lectures/graphs.html
为什么我会收到此错误,如何解决?
joh*_*ose 138
has_key已在Python 3中删除.从文档:
- 删除
dict.has_key()-in改为使用运算符.
这是一个例子:
if start not in graph:
return None
Run Code Online (Sandbox Code Playgroud)
小智 40
在python3中,has_key(key)被替换为__contains__(key)
在python3.7中测试:
a = {'a':1, 'b':2, 'c':3}
print(a.__contains__('a'))
Run Code Online (Sandbox Code Playgroud)
Abh*_*tra 12
has_key在Python 3.0中已被弃用。或者,您可以使用“ in”
graph={'A':['B','C'],
'B':['C','D']}
print('A' in graph)
>> True
print('E' in graph)
>> False
Run Code Online (Sandbox Code Playgroud)
我认为,仅in在确定键是否已存在时才使用它,它被认为是“更多的pythonic” ,例如
if start not in graph:
return None
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
110729 次 |
| 最近记录: |