簡體   English   中英

Python-遞歸創建給定三個不同列表的任意嵌套字典

[英]Python - Recursively create arbitrarily nested dict given three different lists

假設給了我三個列表:根列表,子列表(可以有子列表)和節點列表。 在這些列表中的任何一項上,我都可以調用.children屬性來獲取其子級。

目標是構建一個看起來像這樣的任意嵌套的字典:

{root_item: {child_item: {child_child_item: [node1, node2]}}}

到目前為止的嘗試-在一種方法中,我稱為遞歸方法:

structure = {}
for root in list_of_roots:
    structure[root] = self._build_structure(root)

def _build_structure(self, item)
    if item in list_of_nodes:
        return item
    else:
        for child in item.children:
            self._build_structure(child)

因此,問題在於遞歸方法不返回任何中間內容,僅返回節點(沒有子項的子項)。 我缺少一些東西,需要一些幫助來弄清楚如何解決這個問題。

請記住,我是編程新手。

def _build_structure(self, item)
    if item in list_of_nodes:
        return item
    else:
        return [self._build_structure(child) for child in item.children]

您需要返回您的遞歸調用...如果您需要更多幫助,則需要發布一個最小的list_of_nodes示例...。

暫無
暫無

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

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