如何更正错误“AttributeError: 'dict_keys' object has no attribute 'remove'”?
Posted
技术标签:
【中文标题】如何更正错误“AttributeError: \'dict_keys\' object has no attribute \'remove\'”?【英文标题】:How can I correct the error ' AttributeError: 'dict_keys' object has no attribute 'remove' '?如何更正错误“AttributeError: 'dict_keys' object has no attribute 'remove'”? 【发布时间】:2017-11-18 03:04:29 【问题描述】:我正在尝试使用 dijkstra 算法的最短路径查找器,但它似乎不起作用。无法弄清楚问题是什么。这是代码和错误消息。 (我正在开发 Python 3.5。https://www.youtube.com/watch?v=LHCVNtxb4ss)
graph =
'A': 'B': 10, 'D': 4, 'F': 10,
'B': 'E': 5, 'J': 10, 'I': 17,
'C': 'A': 4, 'D': 10, 'E': 16,
'D': 'F': 12, 'G': 21,
'E': 'G': 4,
'F': 'E': 3,
'G': 'J': 3,
'H': 'G': 3, 'J': 3,
'I': ,
'J': 'I': 8,
def dijkstra(graph, start, end):
D =
P =
for node in graph.keys():
D[node]= -1
P[node]=""
D[start]=0
unseen_nodes=graph.keys()
while len(unseen_nodes) > 0:
shortest=None
node=' '
for temp_node in unseen_nodes:
if shortest==None:
shortest = D[temp_node]
node = temp_node
elif D[temp_node]<shortest:
shortest=D[temp_node]
node=temp_node
unseen_nodes.remove(node)
for child_node, child_value in graph[node].items():
if D[child_node] < D[node] + child_value:
D[child_node] = D[node] + child_value
P[child_node]=node
path = []
node = end
while not (node==start):
if path.count(node)==0:
path.insert(0, node)
node=P[node]
else:
break
path.insert(0, start)
return path
AttributeError: 'dict_keys' 对象没有属性 'remove'
【问题讨论】:
【参考方案1】:在 Python 3 中,dict.keys()
返回没有 remove
方法的 a dict_keys object (a view of the dictionary);不像 Python 2,dict.keys()
返回一个列表对象。
>>> graph = 'a': []
>>> keys = graph.keys()
>>> keys
dict_keys(['a'])
>>> keys.remove('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict_keys' object has no attribute 'remove'
您可以使用list(..)
获取密钥列表:
>>> keys = list(graph)
>>> keys
['a']
>>> keys.remove('a')
>>> keys
[]
unseen_nodes = graph.keys()
到
unseen_nodes = list(graph)
【讨论】:
以上是关于如何更正错误“AttributeError: 'dict_keys' object has no attribute 'remove'”?的主要内容,如果未能解决你的问题,请参考以下文章
如何更正此错误:java.lang.OutOfMemoryError
如何更正错误“AttributeError: 'dict_keys' object has no attribute 'remove'”?