簡體   English   中英

如何從嵌套結構中獲取子孫列表?

[英]How to get the list of children and grandchildren from a nested structure?

鑒於這本親子關系詞典,

{
    2: [8, 7],
    8: [9, 10],
    10: [11],
    15: [16, 17],
}

我想獲得所有孩子、孫子、曾孫等的列表——例如,給定 ID 為2的父母,我想獲得以下列表: [8, 7, 9, 10, 11] 嵌套層數可以無限長。 循環是不可能的。

到目前為止,我能夠實現這個 function 但我不知道如何從中返回:

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

由於循環是不可能的並且順序並不重要,因此最簡單的方法是使用生成器 function。只需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]

如果你想要一個傳統的 function 你可以只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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM