Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用Python打印树?_Python_Tree_Pretty Print - Fatal编程技术网

如何用Python打印树?

如何用Python打印树?,python,tree,pretty-print,Python,Tree,Pretty Print,我有以下类,它表示树的一个节点: 类节点: def uuu init uuu(self,name,parent=None): self.name=名称 self.parent=parent self.children=[] # ... 如果是家长: self.parent.children.append(self) 如何打印这样的树?这是我的解决方案: def print_树(当前_节点,缩进=”,last='updown'): nb_children=lambda节点:求和(node.chi

我有以下类,它表示树的一个节点:

类节点:
def uuu init uuu(self,name,parent=None):
self.name=名称
self.parent=parent
self.children=[]
# ...
如果是家长:
self.parent.children.append(self)
如何打印这样的树?

这是我的解决方案:

def print_树(当前_节点,缩进=”,last='updown'):
nb_children=lambda节点:求和(node.children中的子节点的nb_children(child))+1
size_branch={child:nb_children(child)用于当前_节点中的子节点。children}
“”“为“向上”分支和“向下”分支创建平衡列表。”“”
向上=已排序(当前_node.children,key=lambda node:nb_children(node))
向下=[]
向上和求和(向下节点的大小分支[节点])
使用示例:

shame=Node(“shame”)
良心=节点(“良心”,羞耻)
自我厌恶=节点(“自我厌恶”,羞耻)
尴尬=节点(“尴尬”,羞耻)
自我意识=节点(“自我意识”,尴尬)
羞耻=节点(“羞耻”,尴尬)
懊恼=节点(“懊恼”,尴尬)
discomfiture=节点(“discomfiture”,尴尬)
羞愧=节点(“羞愧”,尴尬)
混乱=节点(“混乱”,尴尬)
打印树(羞耻)
这是输出:

┌良心
├自卑
羞耻┤
│             ┌自我意识
│             ├羞耻
│             ├懊恼
└尴尬┤
├尴尬
├羞愧
└混乱
更新:


我推了PyPi。

太好了!你自己发现的。你的树需要提升自尊:)我只是分享我早上的工作:)很好的解决方案!作为对在Python2上使用它的任何人的提示,您需要在file@GP89您只需使用
#编码:utf-8
就可以了,它更容易记忆,也更有效;-)