如何打印反转的ascii树?

2024-10-01 00:29:18 发布

您现在位置:Python中文网/ 问答频道 /正文

asciitree绘制ASCII树,如下所示:

root
  +--sub1
  +--sub2
  |  +--sub2sub1
  +--sub3
     +--sub3sub1
     |  +--sub3sub1sub1
     +--sub3sub2

有没有提示如何用python打印“反转”树?这里有一个例子:

^{pr2}$

asciitree使用以下节点结构:

class Node(object):
    def __init__(self, name, children):
        self.name = name
        self.children = children

Tags: nameselfascii绘制root例子childrensub1
1条回答
网友
1楼 · 发布于 2024-10-01 00:29:18

您只需反转asciitree的输出:

lines = output.splitlines()[::-1]
width = max(len(l) for l in lines)

reversed = []
for line in lines:
    tree, dashes, label = line.rpartition(' ')
    tree = (tree + dashes)[::-1]
    line = '{1:>{0}}{2}'.format(width - len(tree), label, tree).rstrip()
    reversed.append(line)

print '\n'.join(reversed)

演示:

^{pr2}$

相关问题 更多 >