NoneType对象不可迭代错误
问题描述:
我有任务为Dijkstra的算法编写类。虽然我不能编辑的Dijkstra类:NoneType对象不可迭代错误
class Dijkstra():
# initialize with a string containing the root and a
# weighted edge list
def __init__(self, in_string):
self.root, self.nnodes, self.adj_list = self.convert_to_adj_list(in_string)
self.nodes = [Node(i) for i in range(self.nnodes)]
self.nodes[self.root].key = 0
self.heap = MinHeap(self.nodes)
# the input is expected to be a string
# consisting of the number of nodes
# and a root followed by
# vertex pairs with a non-negative weight
def convert_to_adj_list(self, in_string):
nnodes, root, edges = in_string.split(';')
root = int(root)
nnodes = int(nnodes)
adj_list = {}
edges = [ map(int,wedge.split()) for wedge in edges.split(',')]
for u,v,w in edges:
(adj_list.setdefault(u,[])).append((v,w))
for u in range(nnodes):
adj_list.setdefault(u,[])
这是我的问题:
string = '3; 0; 1 2 8, 2 0 5, 1 0 8, 2 1 3'
print(Dijkstra(string))
Traceback (most recent call last):
File "<pyshell#321>", line 1, in <module>
print(Dijkstra(string))
File "C:\Users\TheDude\Downloads\dijkstra.py", line 71, in __init__
self.root, self.nnodes, self.adj_list = self.convert_to_adj_list(in_string)
TypeError: 'NoneType' object is not iterable
难道我给你append
的返回值?我该如何解决它不W/o编辑 class Djikstra()
坦克供阅读。
答
为了分配
self.root, self.nnodes, self.adj_list = self.convert_to_adj_list(in_string)
工作,convert_to_adj_list
必须返回三个值中的一个元组,待分解为这三个变量。但是,您的方法不会返回任何内容(因此隐式返回None
)。更改convert_to_adj_list
方法是这样的,那么它应该工作:
def convert_to_adj_list(self, in_string):
... your code ...
return root, nnodes, adj_list
+0
谢谢tobias! – TheDude
'convert_to_adj_list'回报'None',因为你没有用一个return语句为它供给。 – miradulo
你应该从'convert_to_adj_list'得到一个返回值,所以将'return adj_list'添加到'convert_to_adj_list'定义的末尾。 –
所以如果我不设置返回值,任何函数都会返回None? 我必须使用Dijkstra类,所以我需要联系老师来解决这个问题。 – TheDude