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