简体   繁体   English

如何在python中解析和打印树

[英]How to parse and print a tree in python

Currently I have data in the following format 目前,我有以下格式的数据

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

This is stored in a list [line1,line2, and so forth] 这存储在列表中[行1,行2,依此类推]

Now I want to print this in the following manner 现在我要以以下方式打印

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

I'm new to python so. 我是python的新手。 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

First we parse the string: 首先我们解析字符串:

data = """A
    A -> B -> C -> D -> Z
    A -> B -> O
    A -> X
    """

lines = [x.split(' -> ') for x in data.split('\n') if x]

This will return 这将返回

[['A'], ['A', 'B', 'C', 'D', 'Z'], ['A', 'B', 'O'], ['A', 'X']]

Then we build it: 然后我们构建它:

def addone(owner, data):
    o = owner.setdefault(data.pop(0), {})
    if data:
        addone(o, data)

root = {}
for line in lines:
    addone(root, line)

Now the root will be: 现在的根将是:

{'A': {'X': {}, 'B': {'C': {'D': {'Z': {}}}, 'O': {}}}}

Finally we display it: 最后我们显示它:

def show(base, data):
    while data:
        k, v = data.pop(0)
        print '%s|-%s' % (base, k)
        if v:
            if data:
                show(base + '| ', v.items())
            else:
                show(base + '  ', v.items())

show("", root.items())

It will output on my place like this: 它将像这样在我的位置输出:

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

O and C has different order, because python dict not remember order, which is easy to change by sort or use collections.OrderedDict O和C具有不同的顺序,因为python dict不记得顺序,可以通过排序或使用集合轻松更改顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM