一直试图打印由以下字典定义的图形的所有路径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")当我运行该函数时print_all_child_paths,我以错误告终list indices must be integers, not str。编译器指向第 40 行,即 while 循环定义: while current_node["child"] in graph:我对错误感到困惑,因为循环的条件是检查键是否在字典中。谁能帮我这个?提前致谢。
2 回答
米脂
TA贡献1836条经验 获得超3个赞
一旦你current_node = graph[current_node["child"]]
在循环的第一次迭代中做,current_node
就变成一个列表,因为graph
字典的所有值都是列表。
但是,紧接着您的代码尝试current_node["child"]
在循环条件下执行,但是current_node
,作为列表,不能用字符串索引,因此出现错误。
慕无忌1623718
TA贡献1744条经验 获得超4个赞
每个node
都是字典列表。current_node
列表也是如此,只能使用整数索引访问。您正在尝试将其作为带有字符串键的字典来访问。您需要遍历节点列表以访问每个字典。
for child in current node: while child["child"] in graph:
添加回答
举报
0/150
提交
取消