gpt4 book ai didi

python - 如何在Python中解析和打印树

转载 作者:行者123 更新时间:2023-12-01 05:30:29 24 4
gpt4 key购买 nike

目前我有以下格式的数据

A
A -> B -> C -> D -> Z
A -> B -> O
A -> X

这存储在列表中 [line1、line2 等]

现在我想按以下方式打印它

 A
|- X
|- B
|- O
|- C
|- D
|- Z

我是Python新手,所以。我正在考虑在数组中的每个元素中找到“->”并用空格替换。我不知道该往前走。

最佳答案

这里有一些代码可以帮助您入门(根据需要添加您自己的美化):

>>> def make_links(data):
'Create a dictionary mapping nodes to a set of their successors'
links = {}
for row in data:
nodes = row.replace(' ', '').split('->')
for a, b in zip(nodes[:-1], nodes[1:]):
links.setdefault(a, set()).add(b)
return links

>>> def draw_tree(links, start, depth=0):
'Recursively print a tree from a given starting point and given depth'
print(' ' * depth + start)
for node in sorted(links.get(start, [])):
draw_tree(links, node, depth+1)

>>> data = ['A', 'A -> B -> C -> D -> Z', 'A -> B -> O', 'A -> X']

>>> links = make_links(data)
>>> links
{'A': {'X', 'B'}, 'C': {'D'}, 'B': {'C', 'O'}, 'D': {'Z'}}

>>> draw_tree(links, start='A')
A
B
C
D
Z
O
X

关于python - 如何在Python中解析和打印树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20386727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com