[英]Recursively going through a dictionary
所以我有字典。
dictionary = {"one": ["two"], "two": ["three"], "three": [None]}
如果給我三個,如何遞歸地查找一個函數? 例如:一個最終變成三個嗎? 是的,因為一個->兩個->三個相同。 三->二->一
到目前為止,我已經嘗試在字典中使用列表推導;
def function(start, end, dict_to_check):
if dict_to_check[end] == start:
return True
else:
var = {key: value for key, value in dict_to_check.items() if value == start}
return var
但這不使用遞歸,我也不知道該怎么做
您可以嘗試以下方法:
start = "one"
end = "three"
dictionary = {"one": ["two"], "two": ["three"], "three": [None]}
def check(s):
if not dictionary[s][0]:
return "Not found"
if dictionary[s][0] == end:
return "found"
else:
return check(dictionary[s][0])
print(check(start))
輸出:
found
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.