我从最小生成树算法创建了以下数据:
links = [("Earl","Bob"),("Bob","Sam"),("Bob","Leroy"),("Leroy","Harry")]
我需要将数据转换为以下json树:
{
"id": "Earl",
"name": "Earl",
"children": [
{
"id": "Bob",
"name": "Bob",
"children": [
{
"id": "Leroy",
"name": "Leroy",
"children": [
{
"id": "Harry",
"name": "Harry"
}
]
},
{
"id": "Sam",
"name": "Sam"
}
]
}
]
}
我有以下脚本可以工作,除了它将一个名为“Root”的根节点添加到我不想要的树中:
import json
links = [("Earl","Bob"),("Bob","Sam"),("Bob","Leroy"),("Leroy","Harry")]
parents, children = zip(*links)
root_nodes = {x for x in parents if x not in children}
for node in root_nodes:
links.append(('Root', node))
def get_nodes(node):
d = {}
d['id'] = node
d['name'] = node
children = get_children(node)
if children:
d['children'] = [get_nodes(child) for child in children]
return d
def get_children(node):
return [x[1] for x in links if x[0] == node]
tree = get_nodes('Root')
print(json.dumps(tree, indent=2))
### output below ###
{
"children": [
{
"children": [
{
"children": [
{
"id": "Sam",
"name": "Sam"
},
{
"children": [
{
"id": "Harry",
"name": "Harry"
}
],
"id": "Leroy",
"name": "Leroy"
}
],
"id": "Bob",
"name": "Bob"
}
],
"id": "Earl",
"name": "Earl"
}
],
"id": "Root",
"name": "Root"
}
我需要的是不要添加假的“Root”作为根节点。根应该只是links
中没有父节点的任何现有节点(根据第一个json示例)。换句话说,树的根不一定必须是Earl,它可以是没有父母的任何节点。然后树可以从那里开始扩展。
也许有更好的算法来做这个而不是试图修改它?
答案 0 :(得分:-1)
tree = get_nodes('Root');
tree = tree.children[0];
print(json.dumps(tree, indent=2));
答案 1 :(得分:-1)
这不是因为你已经将伯爵加入了Root的孩子吗?用:
links.append(('Root', node))
print links # [('Earl', 'Bob'), ('Bob', 'Sam'), ('Bob', 'Leroy'), ('Leroy', 'Harry'), ('Root', 'Earl')]
现在当您为children = get_children(node)
运行node = 'Root'
时,您将获得True
。