第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

打印圖形的路徑,列表索引必須是整數(shù),而不是 str

打印圖形的路徑,列表索引必須是整數(shù),而不是 str

嗶嗶one 2021-11-09 20:06:44
一直試圖打印由以下字典定義的圖形的所有路徑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ò)誤。


查看完整回答
反對(duì) 回復(fù) 2021-11-09
?
慕無(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:


查看完整回答
反對(duì) 回復(fù) 2021-11-09
  • 2 回答
  • 0 關(guān)注
  • 185 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)