python如何制作一个任意列表,Python-递归创建给定三个不同列表的任意嵌套字典...

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]

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值