我有如下数据集:
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 在这里很有用,但我不知道如何实现这段代码。任何帮助将不胜感激。