鑒于這本親子關系詞典,
{
2: [8, 7],
8: [9, 10],
10: [11],
15: [16, 17],
}
我想得到所有孩子、孫子、曾孫等的串列——例如,如果父母有一個 ID 2,我想得到以下串列:[8, 7, 9, 10, 11]。嵌套層數可以無限長。回圈是不可能的。
到目前為止,我能夠實作此功能,但我不知道如何從中回傳:
links = {
2: [8, 7],
8: [9, 10],
10: [11],
15: [16, 17],
}
def get_nested_children(parent_uid, acc = []):
if parent_uid in links:
acc = acc links[parent_uid]
print("[in loop]", acc)
for child_uid in links[parent_uid]:
get_nested_children(child_uid, acc)
else:
return acc
print(get_nested_children(2))
哪些輸出:
[in loop] [8, 7]
[in loop] [8, 7, 9, 10]
[in loop] [8, 7, 9, 10, 11]
None
uj5u.com熱心網友回復:
由于回圈是不可能的并且順序并不重要,因此最簡單的方法是使用生成器函式。只有yield孩子和yield from遞回的結果。這會給你一個深度優先的結果:
links = {
2: [8, 7],
8: [9, 10],
10: [11],
15: [16, 17],
}
def get_nested_children(parent_uid):
for child_uid in links.get(parent_uid, []):
yield child_uid
yield from get_nested_children(child_uid)
list(get_nested_children(2))
# [8, 9, 10, 11, 7]
如果你想要一個傳統的函式,你可以只是append每個孩子,然后extend遞回到一個本地串列的結果,你可以回傳:
def get_nested_children(parent_uid):
res = []
for child_uid in links.get(parent_uid, []):
res.append(child_uid)
res.extend(get_nested_children(child_uid))
return res
get_nested_children(2)
# [8, 9, 10, 11, 7]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/535802.html
標籤:Python递归亲子孙子
