擅长:python、mysql、java
<p>使用字典(如果需要<code>collections.OrderedDict</code>)可以使循环更容易。
使用推荐的<code>anytree</code>包,它将提供所需的图形输出,整个代码将只是:</p>
<pre><code>import anytree
# parent-child relations
table = [
[1, 2],
[5, 3],
[2, 5],
[2, 6],
[2, 4],
[6, 7],
]
def build_tree_recursively(p_num, p_node):
for c_num in parent_children[p_num]: # add children
c_node = anytree.Node(str(c_num), parent=p_node)
if c_num in parent_children: # dive into
build_tree_recursively(c_num, c_node)
# map parents to list of children
parent_children = {}
for p, c in table: # numbers
if p in parent_children:
parent_children[p].append(c)
else:
parent_children[p] = [c]
p = 1 # assuming single root node (else add loop over elements not in column B)
tree = anytree.Node(str(p))
build_tree_recursively(p, tree)
# render
for pre, fill, node in anytree.RenderTree(tree):
print("{}{}".format(pre, node.name))
</code></pre>