Ale*_*ndr 8 python tree hierarchical-trees
我有一个带有attrs的元素列表:parent,level,is_leaf_node,is_root_node,is_child_node.
我想将此列表转换为层次结构dict.输出字典的示例:
{
'Technology':
{
'Gadgets':{},
'Gaming':{},
'Programming':
{
'Python':{},
'PHP':{},
'Ruby':{},
'C++':{}
},
'Enterprise':{},
'Mac':{},
'Mobile':{},
'Seo':{},
'Ui':{},
'Virtual Worlds':{},
'Windows':{},
},
'News':{
'Blogging':{},
'Economics':{},
'Journalism':{},
'Politics':{},
'News':{}
},}
Run Code Online (Sandbox Code Playgroud)
我不知道算法.怎么做?
Mat*_* S. 12
这是一个不太复杂的递归版本,如chmod 700所描述的.完全未经测试的当然:
def build_tree(nodes):
# create empty tree to fill
tree = {}
# fill in tree starting with roots (those with no parent)
build_tree_recursive(tree, None, nodes)
return tree
def build_tree_recursive(tree, parent, nodes):
# find children
children = [n for n in nodes if n.parent == parent]
# build a subtree for each child
for child in children:
# start new subtree
tree[child.name] = {}
# call recursively to build a subtree for current node
build_tree_recursive(tree[child.name], child, nodes)
Run Code Online (Sandbox Code Playgroud)