一直試圖打印由以下字典定義的圖形的所有路徑graph = { "a": [ {"child": "b", "cost": 5}, {"child": "e", "cost": 8} ], "b": [ {"child": "c", "cost": 7}, {"child": "f", "cost": 2} ], "d": [ {"child": "g", "cost": 3}, ], "e": [ {"child": "d", "cost": 3}, {"child": "f", "cost": 6} ], "f": [ {"child": "c", "cost": 1}, ], "g": [ {"child": "h", "cost": 10} ], "h": [ {"child": "f", "cost": 4} ]}def print_all_child_paths(graph, node_name): node = graph[node_name] if len(node) == 0: print("No children under this node") else: x = 1 for child_node in node: print("Path number " + str(x) + ": ") print(node_name + " -> ") current_node = child_node while current_node["child"] in graph: print(current_node["child"] + " -> ") current_node = graph[current_node["child"]] print("END.") x += 1 print("End of paths")print_all_child_paths(graph, "a")當(dāng)我運(yùn)行該函數(shù)時(shí)print_all_child_paths,我以錯(cuò)誤告終list indices must be integers, not str。編譯器指向第 40 行,即 while 循環(huán)定義: while current_node["child"] in graph:我對(duì)錯(cuò)誤感到困惑,因?yàn)檠h(huán)的條件是檢查鍵是否在字典中。誰(shuí)能幫我這個(gè)?提前致謝。
2 回答

米脂
TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超3個(gè)贊
一旦你current_node = graph[current_node["child"]]
在循環(huán)的第一次迭代中做,current_node
就變成一個(gè)列表,因?yàn)?code>graph字典的所有值都是列表。
但是,緊接著您的代碼嘗試current_node["child"]
在循環(huán)條件下執(zhí)行,但是current_node
,作為列表,不能用字符串索引,因此出現(xiàn)錯(cuò)誤。

慕無(wú)忌1623718
TA貢獻(xiàn)1744條經(jīng)驗(yàn) 獲得超4個(gè)贊
每個(gè)node
都是字典列表。current_node
列表也是如此,只能使用整數(shù)索引訪(fǎng)問(wèn)。您正在嘗試將其作為帶有字符串鍵的字典來(lái)訪(fǎng)問(wèn)。您需要遍歷節(jié)點(diǎn)列表以訪(fǎng)問(wèn)每個(gè)字典。
for child in current node: while child["child"] in graph:
添加回答
舉報(bào)
0/150
提交
取消