asciitree绘制ASCII树,如下所示:
root
+--sub1
+--sub2
| +--sub2sub1
+--sub3
+--sub3sub1
| +--sub3sub1sub1
+--sub3sub2
任何提示如何用python打印'反向'树?这是一个例子:
sub3sub2--+
sub3sub1sub1--+ |
sub3sub1--+
sub3--+
sub2sub1--+ |
sub2--+
sub1--+
root
asciitree使用以下节点结构:
class Node(object):
def __init__(self, name, children):
self.name = name
self.children = children
答案 0 :(得分:1)
你可以反转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)
演示:
>>> output = '''\
... root
... +--sub1
... +--sub2
... | +--sub2sub1
... +--sub3
... +--sub3sub1
... | +--sub3sub1sub1
... +--sub3sub2
... '''
>>> 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)
sub3sub2--+
sub3sub1sub1--+ |
sub3sub1--+
sub3--+
sub2sub1--+ |
sub2--+
sub1--+
root