Python-给定三个不同的列表,以递归方式创建任意嵌套的dict [英] Python - Recursively create arbitrarily nested dict given three different lists

查看:244
本文介绍了Python-给定三个不同的列表,以递归方式创建任意嵌套的dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设给我三个列表:根列表,子列表(可以有子列表)和节点列表.在这些列表中的任何一项上,我都可以调用.children属性来获取其子项.

Suppose I am given three lists: a list of roots, a list of children (which can have children), and a list of nodes. On any of the items in these lists, I can call use an attribute .children to get its children.

目标是构建一个看起来像这样的任意嵌套的字典:

The goal is to construct an arbitrarily nested dictionary that could look like this:

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

到目前为止,我的尝试-在一种方法中,我称为递归方法:

My attempt so far -- in one method, I call a recursive method:

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)

因此,问题在于递归方法不返回任何中间内容,仅返回节点(没有子项的子项).我缺少了一些东西,需要一些帮助来弄清楚如何解决这个问题.

So, the problem with this is that the recursive method doesn't return any of the intermediate stuff, just the nodes (children without children). I am missing something and need some help figuring out how to go about this.

请记住,我是编程新手.

Please keep in mind that I am new to programming.

推荐答案

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 .....

you need to return your recursive call ... if you need more help you will need to post a minimal example of list_of_nodes ....

这篇关于Python-给定三个不同的列表,以递归方式创建任意嵌套的dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆