我有如下数据集:

A    B

1    2
5    3
2    5
3


下面的代码为我提供了以下输出:

def all_paths(table, root):
    # convert table structure to adjacency list
    children = {}
    for node, child in table:
        if child:
             children[node] = children.setdefault(node, []) + [child]

        # generator for iteration over all paths from a certain node
        def recurse(path):
            yield path
            if path[-1] in children:
                for child in children[path[-1]]: # recursive calls for all child nodes
                    yield from recurse(path + [child])

        return recurse([root])

# Sample data in simple list format
table = [
[1, 2],
[5, 3],
[2, 5],
[2, 6],
[2, 4],
[6, 7],
]

# Output all paths from node 1
for path in all_paths(table, 1):
    print(path)

Output:
[1]
[1, 2]
[1, 2, 5]
[1, 2, 5, 3]
[1, 2, 6]
[1, 2, 6, 7]
[1, 2, 4]


但是我在这里想要以如下所示的渲染树格式打印输出:

1
└── 2
    |── 5
    |   └──3
    |── 6
    |   └──7
    └── 4


我知道python库Anytree在这里很有用,但我不知道如何实现此代码。任何帮助将不胜感激。

最佳答案

使用字典(如果需要,请使用collections.OrderedDict)会使循环更容易。
使用推荐的anytree包,它将提供所需的图形输出,并且整个代码将是:

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))

08-24 14:05