我的代碼如下:
def und1(d):
for i in d:
if type(d[i])==dict:
und1(d[i])
else:
yield({i:d[i]})
Dict1 = {1: 'Geeks', 2: 'For', 3: 'Geeks',4:{5:'wevcn '}}
for z in und1(Dict1):
print(z)
我目前正在獲得輸出:
{1: 'Geeks'}
{2: 'For'}
{3: 'Geeks'}
預期輸出:
{1: 'Geeks'}
{2: 'For'}
{3: 'Geeks'}
{5:'wevcn'}
問題:我的函式沒有呼叫 recurisve 函式,而是回傳 null。有人能告訴我為什么嗎?
uj5u.com熱心網友回復:
您的代碼應該使用yield from并且可以像這樣簡化:
def und1(d):
for k, v in d.items():
if isinstance(v, dict):
yield from und1(v)
else:
yield {k: v}
dict1 = {1: 'Geeks', 2: 'For', 3: 'Geeks', 4: {5: 'wevcn '}}
for z in und1(dict1):
print(z)
這isinstance()對于檢查“某物是否是...”特別有用,并且通過迭代.items()a dict,您可以輕松訪問鍵和值,因此您不必dict再次索引。
輸出:
{1: 'Geeks'}
{2: 'For'}
{3: 'Geeks'}
{5: 'wevcn '}
在您的代碼中,從函式回傳了一個生成器(因為它確實為非 dict 專案產生了收益),并且由于您呼叫了該函式,但沒有將函式結果分配給任何東西,因此該生成器被丟棄了。
您可以將函式結果分配給一個變數并對其進行迭代,但不需要您想要的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/371680.html
