我想以下列风格构建“图表”:
{
"name":cersei
"children": [
{
"name": "baratheon",
"children": [
{
"name": "cersei",
"children": []
},
{
"name": "baratheon",
"children": [],
}
],
},
{
"name": "joffrey",
"children": [
{
"name": "robert",
"children": []
},
{
"name": "cersei",
"children": []
}
]
}
]
}
但我是通过深度优先构建的。这意味着“儿童”的第一个元素是完全构建的,之后构建了“儿童”的第二个元素。这是递归函数:
def recurse(dicts, depth):
if depth >=0:
dicts["children"] = []
child_elements = [] //do something to get your child-elements
for child in child_elements:
if depth >=0:
child_dict = dict(name=word[0])
dicts["children"].append(child_dict)
recurse(child_dict, depth-1)
我如何更改它首先构建整个“级别”的代码,然后将子级子项附加到其中?我有问题,我不知道如何调用1级字典,因为它在字典中的字典......
亲切的问候并感谢你的帮助,FFoDWindow。
-------------------- **** **** UPDATE ------------------ --------- 我自己解决了这个问题。实际上这很简单。我只需要在一个额外的列表中保存临时构建“孩子”元素。现在树是广度优先的。这是我的递归功能:
def recurse( input_dict, level_list, depth):
next_level_list = []
for dictionary in input_dict:
child_elements = [...] //get the data for your children
for child_element in child_elements:
dictionary["children"].append = dict(name = child_element)
next_level_list.append(dictionary["children"][-1])
if depth >=0:
recurse(input_dict, next_level_list, depth-1)