我有一個帶有嵌套字典和特定數字的函式(在我撰寫的代碼中它等于 1)我需要撰寫一個遞回函式來遍歷字典并僅回傳映射到等于特定選擇數字的鍵的值是我寫的
def nested_get(d, key):
res=[]
for i in d.keys():
if i == key:
res.append(d[i])
return res
if type(d[i]) is dict:
another = nested_get(d[i], key)
if another is not None:
return res another
return []
列印(nested_get({1:{1:"c",2:"b"},2:"b"},1))
我需要它回傳 ['c'] 但它回傳 [{1:'c',2:'b'}]
uj5u.com熱心網友回復:
您的程式永遠不會到達 ,if type(d[i]) is dict:因為它在回圈if的第一次迭代的第一條陳述句中回傳for。
檢查存盤在鍵中的值是否是dict第一個,并且直到if陳述句之后才回傳。您不需要return []最后,因為res如果沒有附加任何內容,它將是空的。
def nested_get(d, key):
res=[]
for i in d.keys():
if type(d[i]) is dict:
res.extend(nested_get(d[i], key))
else:
if i == key:
res.append(d[i])
return res
print(nested_get({1:{1:"c",2:"b"},2:"b"},1))
print(nested_get( {1:{1:"a",2:"b"},2:{1:{1:"c",2:"b"},2:"b"}},1))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/383343.html
上一篇:二叉樹中數字的總和
下一篇:在串列中迭代串列,遞回
