我試圖創建一個函式,該函式使用另一個串列(index_list)作為索引路徑從串列(xs)中查找值。
我的功能應該是這樣的:
xs = [[[1, 2], 3], [4, 5, [6, 7]], 8, [9, 10, 11]]
>>> recursive_index(xs, [1, 2, 0])
6
到目前為止,我有:
def recursive_index(xs: List, index_path):
if not index_path:
return 0
return recursive_index(xs, index_path[1:])
然而,這只是為所有內容回傳 0,但我不知道基本情況應該是什么。
uj5u.com熱心網友回復:
您已經很接近了,但是您忘記了在每次遞回時實際上都需要對串列進行索引,以便在每次遞回時進一步深入。這樣,當您到達基本情況時,變數xs將存盤正確的結果,您可以回傳它。
這就是代碼的樣子:
def recursive_index(xs: List, index_path):
if not index_path:
return xs
return recursive_index(xs[index_path[0]], index_path[1:])
uj5u.com熱心網友回復:
你要這個:
def recursive_index(xs, index_path):
if not index_path:
# if path is exhausted just return current element
return xs
# use first index on current list and recurse with the remaining path
return recursive_index(xs[index_path[0]], index_path[1:])
uj5u.com熱心網友回復:
xs您的遞回函式應繼續從第一個索引處提取值,index_path直到路徑的其余部分不再有索引:
def recursive_index(xs, index_path):
index, *rest = index_path
value = xs[index]
return recursive_index(value, rest) if rest else value
uj5u.com熱心網友回復:
接受的答案已經解釋了如何修復您的遞回函式。
請注意,迭代函式也同樣有效:
def iterative_index(xs, index_path):
for idx in index_path:
xs = xs[idx]
return xs
或使用reduce:
from functools import reduce
def reduce_index(xs, index_path):
return reduce(list.__getitem__, index_path, xs)
測驗:
xs = [[[1, 2], 3], [4, 5, [6, 7]], 8, [9, 10, 11]]
index_path = (1, 2, 0)
print( iterative_index(xs, index_path) )
# 6
print( reduce_index(xs, index_path) )
# 6
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/482927.html
上一篇:根據子條件過濾嵌套的物件陣列
下一篇:如何在遞回函式中獲取下一行
