图形的打印路径,列表索引必须是整数,而不是 str
Printing paths of a graph, list indices must be integers, not str
一直在尝试打印由以下字典定义的图形的所有路径
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:
我对错误感到困惑,因为循环的条件是检查键是否在字典中。谁能帮我解决这个问题?
提前致谢。
只要在循环的第一次迭代中执行 current_node = graph[current_node["child"]]
,current_node
就会变成一个列表,因为 graph
字典的所有值都是列表。
但是,紧接着您的代码尝试在循环条件下执行 current_node["child"]
,但是 current_node
作为一个列表,不能用字符串索引,因此出现错误。
每个 node
是一个字典列表。所以 current_node
是一个列表,只能用整数索引访问。您正在尝试将其作为具有字符串键的字典进行访问。您需要遍历节点列表才能访问每个字典。
for child in current node:
while child["child"] in graph:
一直在尝试打印由以下字典定义的图形的所有路径
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:
我对错误感到困惑,因为循环的条件是检查键是否在字典中。谁能帮我解决这个问题?
提前致谢。
只要在循环的第一次迭代中执行 current_node = graph[current_node["child"]]
,current_node
就会变成一个列表,因为 graph
字典的所有值都是列表。
但是,紧接着您的代码尝试在循环条件下执行 current_node["child"]
,但是 current_node
作为一个列表,不能用字符串索引,因此出现错误。
每个 node
是一个字典列表。所以 current_node
是一个列表,只能用整数索引访问。您正在尝试将其作为具有字符串键的字典进行访问。您需要遍历节点列表才能访问每个字典。
for child in current node:
while child["child"] in graph: