【问题标题】:How to print a tree in Python?如何在 Python 中打印一棵树?
【发布时间】:2015-06-17 14:03:08
【问题描述】:

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

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

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

如何打印这样的树?

【问题讨论】:

    标签: python tree pretty-print


    【解决方案1】:

    这是我的解决方案:

    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 上推送了a more complete solution

    【讨论】:

    • 太棒了!你自己找到的。
    • 你的树需要提升自尊 :)
    • 我只是分享我早上的工作as StackOverflow encourages it :)
    • 不错的解决方案!作为在 python 2 上使用它的任何人的说明,您需要在文件顶部使用# -*- coding: utf-8 -*-
    • @GP89 ​​你可以使用# coding: utf-8 它更容易记住并且有效;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2020-05-17
    • 2022-11-11
    • 2023-03-17
    相关资源
    最近更新 更多