這是相當簡單的使用兩遍方法做:首先,構造一個節點爲每個單獨的線。然後,將每個節點連接到其子節點。
with open("data.txt") as file:
lines = file.read().split("\n")
#remove header line.
lines = lines[1:]
entries = {}
#create an entry for each child node.
for line in lines:
name, level, child, size = line.split()
entries[child] = {"name": child, "size": int(size), "children": []}
#we now have an entry for all nodes that are a child of another node.
#but not for the topmost parent node, so we'll make one for it now.
parents = set(line.split()[0] for line in lines)
children = set(line.split()[2] for line in lines)
top_parent = (parents - children).pop()
#(just guess the size, since it isn't supplied in the file)
entries[top_parent] = {"name": top_parent, "size": 5000, "children": []}
#hook up each entry to its children
for line in lines:
name, level, child, size = line.split()
entries[name]["children"].append(entries[child])
#the nested structure is ready to use!
structure = entries[top_parent]
#display the beautiful result
import pprint
pprint.pprint(structure)
結果:
{'children': [{'children': [{'children': [], 'name': 'xxx', 'size': 45},
{'children': [], 'name': 'xxy', 'size': 29},
{'children': [], 'name': 'xxz', 'size': 28},
{'children': [], 'name': 'xxa', 'size': 4}],
'name': 'aaab',
'size': 2952},
{'children': [{'children': [{'children': [],
'name': 'ppp',
'size': 4},
{'children': [],
'name': 'qqq',
'size': 2}],
'name': 'ddd',
'size': 7},
{'children': [], 'name': 'xxt', 'size': 4},
{'children': [], 'name': 'xxu', 'size': 1},
{'children': [], 'name': 'xxv', 'size': 1}],
'name': 'aaac',
'size': 251},
{'children': [], 'name': 'aaad', 'size': 222}],
'name': 'aaa',
'size': 5000}
編輯:您可以通過使用del
語句刪除葉節點的children
屬性。
#execute this after the "hook up each entry to its children" section.
#remove "children" from leaf nodes.
for entry in entries.itervalues():
if not entry["children"]:
del entry["children"]
結果:
{'children': [{'children': [{'name': 'xxx', 'size': 45},
{'name': 'xxy', 'size': 29},
{'name': 'xxz', 'size': 28},
{'name': 'xxa', 'size': 4}],
'name': 'aaab',
'size': 2952},
{'children': [{'children': [{'name': 'ppp', 'size': 4},
{'name': 'qqq', 'size': 2}],
'name': 'ddd',
'size': 7},
{'name': 'xxt', 'size': 4},
{'name': 'xxu', 'size': 1},
{'name': 'xxv', 'size': 1}],
'name': 'aaac',
'size': 251},
{'name': 'aaad', 'size': 222}],
'name': 'aaa',
'size': 5000}
你如何確定 「AAA」 的大小爲5000? – Kevin