这是一个更简单的方法。(根据我从托马斯答案中了解到的那样进行编辑,可以按任意顺序指定节点):第1遍创建节点(即,将它们添加到节点字典中),而第2遍然后创建parent <-> children结构。
进行以下假设:没有循环(由Garret R指出,在这种情况下尚不清楚预期的输出是什么),没有丢失的边,没有丢失的树根。
a = [(1, 1), (2, 1), (3, 1), (4, 3), (5, 3), (6, 3), (7, 7), (8, 7), (9, 7)]
# pass 1: create nodes dictionary
nodes = {}
for i in a:
id, parent_id = i
nodes[id] = { 'id': id }
# pass 2: create trees and parent-child relations
forest = []
for i in a:
id, parent_id = i
node = nodes[id]
# either make the node a new tree or link it to its parent
if id == parent_id:
# start a new tree in the forest
forest.append(node)
else:
# add new_node as child to parent
parent = nodes[parent_id]
if not 'children' in parent:
# ensure parent has a 'children' field
parent['children'] = []
children = parent['children']
children.append(node)
print forest
编辑:为什么您的解决方案无法按预期工作?
这是有关顶层的提示:您要获取的输出是树 列表 。但是,要处理的变量(d)必须是字典,因为在函数set_nested中,您将setdefaults方法应用于该变量。