如何在Python中打印树?

clemtoy

我有以下代表树的节点的类:

class Node:
    def __init__(self, name, parent=None):
        self.name = name
        self.parent = parent
        self.children = []
        # ...

        if parent:
            self.parent.children.append(self)

如何打印这样的树?

clemtoy

这是我的解决方案:

def print_tree(current_node, indent="", last='updown'):

    nb_children = lambda node: sum(nb_children(child) for child in node.children) + 1
    size_branch = {child: nb_children(child) for child in current_node.children}

    """ Creation of balanced lists for "up" branch and "down" branch. """
    up = sorted(current_node.children, key=lambda node: nb_children(node))
    down = []
    while up and sum(size_branch[node] for node in down) < sum(size_branch[node] for node in up):
        down.append(up.pop())

    """ Printing of "up" branch. """
    for child in up:     
        next_last = 'up' if up.index(child) is 0 else ''
        next_indent = '{0}{1}{2}'.format(indent, ' ' if 'up' in last else '│', " " * len(current_node.name))
        print_tree(child, indent=next_indent, last=next_last)

    """ Printing of current node. """
    if last == 'up': start_shape = '┌'
    elif last == 'down': start_shape = '└'
    elif last == 'updown': start_shape = ' '
    else: start_shape = '├'

    if up: end_shape = '┤'
    elif down: end_shape = '┐'
    else: end_shape = ''

    print '{0}{1}{2}{3}'.format(indent, start_shape, current_node.name, end_shape)

    """ Printing of "down" branch. """
    for child in down:
        next_last = 'down' if down.index(child) is len(down) - 1 else ''
        next_indent = '{0}{1}{2}'.format(indent, ' ' if 'down' in last else '│', " " * len(current_node.name))
        print_tree(child, indent=next_indent, last=next_last)

使用示例:

shame = Node("shame")

conscience = Node("conscience", shame)
selfdisgust = Node("selfdisgust", shame)
embarrassment = Node("embarrassment", shame)

selfconsciousness = Node("selfconsciousness", embarrassment)
shamefacedness = Node("shamefacedness", embarrassment)
chagrin = Node("chagrin", embarrassment)
discomfiture = Node("discomfiture", embarrassment)
abashment = Node("abashment", embarrassment)
confusion = Node("confusion", embarrassment)

print_tree(shame)

这是输出:

     ┌conscience
     ├self-disgust
shame┤
     │             ┌self-consciousness
     │             ├shamefacedness
     │             ├chagrin
     └embarrassment┤
                   ├discomfiture
                   ├abashment
                   └confusion

更新:

在PyPi上推出了更完整的解决方案

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何在终端中打印目录树

来自分类Dev

如何在Rshiny中打印出rpart树结果文本

来自分类Dev

如何在python中打印%

来自分类Dev

如何在python中解析括号树?

来自分类Dev

如何在python中绘制生存树

来自分类Dev

如何在python中遍历json树

来自分类Dev

如何在(python)中解析树库?

来自分类Dev

在python中打印文本树

来自分类Dev

如何在antrr4中使用python2运行时打印解析树

来自分类Dev

如何在python中打印原始unicode?

来自分类Dev

如何在python数组中打印列?

来自分类Dev

如何在Python中打印对象

来自分类Dev

如何在python中打印缺少的行?

来自分类Dev

如何在Python中打印字典

来自分类Dev

如何在python中暂停循环打印

来自分类Dev

如何在python中打印特殊字符

来自分类Dev

如何在Python中以斜体打印文本?

来自分类Dev

如何在python中打印最小集

来自分类Dev

如何在Python中打印Viariable的位

来自分类Dev

如何在python中打印C格式

来自分类Dev

如何在python中打印子矩阵?

来自分类Dev

如何在 Python 中打印大数?

来自分类Dev

如何在python中替换n元树中的节点?

来自分类Dev

如何在C中按级别打印二叉树中的元素

来自分类Dev

如何在C中按级别打印二叉树中的元素

来自分类Dev

如何在C中实现打印树的所有路径的功能?

来自分类Dev

如何在C中实现打印树的所有路径的功能?

来自分类Dev

如何在python中获取最小生成树矩阵

来自分类Dev

如何在以python字典表示的树中搜索单词?