[英]How to perform recursion in python dictionary
我有一本字典,我想用它來創建一棵樹。 這個想法是獲取指定索引的值,將其附加到列表中。 將此值用作字典下一項中的索引,並重復該過程,直到我們得到 None
我的字典
dict = {
'A' : 'AF',
'BF': 'B',
'AF': 'Z',
'Z' : None,
'B' : 'B'
}
我可以遍歷 dict 並獲得第一個值,但我無法通過 dict 遞歸循環的更好方法。
注意 x 是我想指定的索引參數。即 A、BF、AF、Z 或 B
def tree(x,dict):
result = []
for value in dict:
result.append(value)
#stuck somewhere here.
#I would like to use this value as an index again and pick next value.
#Do this until I have no further relation
#print final results in a list
print result
當調用 tree(x,dict) 時,取 x = 'A' 預期結果應為:
['A','AF','Z']
感謝您的幫助和貢獻。
非遞歸版本要快得多,但有一個看起來不錯
>>> def tree(D, x):
if x is None:
return []
else:
return [x] + tree(D, D[x])
>>> tree(D, 'A')
['A', 'AF', 'Z']
或者作為單線:
def tree(D, x):
return [] if x is None else [x] + tree(D, D[x])
這將具有二次運行時間,因為它每次添加兩個列表,但如果您想要性能,您只需使用.append
,然后無論如何只使用循環會更實用。
def tree(x,dict):
old_value = x
while True:
value = dict.get(old_value)
if not value:
break
result.append(value)
print result
您還可以嘗試使用遞歸生成器:
data = {
'A' : 'AF',
'BF': 'B',
'AF': 'Z',
'Z' : None,
'B' : 'B'
}
def tree(key):
value = data.get(key)
yield key
if value is not None:
for value in tree(value):
yield value
for value in tree("A"):
# Do something with the value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.