如何在python中解析和打印树 [英] How to parse and print a tree in python

查看:212
本文介绍了如何在python中解析和打印树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前我具有以下格式的数据

Currently I have data in the following format

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

此内容存储在列表中[第1行,第2行,依此类推]

This is stored in a list [line1,line2, and so forth]

现在我要以以下方式打印

Now I want to print this in the following manner

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

我是python的新手.我当时想在数组中的每个元素中找到'->'并替换为空格.我不知道前进.

I'm new to python so. I was thinking of finding '->' in each element in array and replacing with space. I don't know to go forward.

推荐答案

以下是一些入门代码(根据需要添加自己的美化名称):

Here is a little code to get you started (add your own beautifications as needed):

>>> 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中解析和打印树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆