我有一個最小生成樹算法創建了以下數據:創建JSON樹未知根
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"
}
我需要的是不要添加假「根」作爲根節點。根應該只是links
中沒有父節點的任何現有節點(按照第一個json示例)。換句話說,樹的根不一定是伯爵,它可以是任何沒有父母的節點。樹可以從那裏開始擴展。
也許有更好的算法來做到這一點,而不是試圖修改這個?
tree = tree.children [0]結果爲:AttributeError:'dict'對象沒有屬性'children' – darkpool
對不起,忘記了python語法了一下。 'tree = tree.get(「children」)[0]' – exec