【发布时间】:2013-11-27 12:25:49
【问题描述】:
我正在寻找一种可能的树打印实现,它以用户友好的方式打印树,而不是作为对象的实例。
我在网上遇到了这个解决方案:
来源:http://cbio.ufs.ac.za/live_docs/nbn_tut/trees.html
class node(object):
def __init__(self, value, children = []):
self.value = value
self.children = children
def __repr__(self, level=0):
ret = "\t"*level+repr(self.value)+"\n"
for child in self.children:
ret += child.__repr__(level+1)
return ret
此代码以下列方式打印树:
'grandmother'
'daughter'
'granddaughter'
'grandson'
'son'
'granddaughter'
'grandson'
是否可以在不改变__repr__方法的情况下获得相同的结果,因为我将它用于其他目的。
编辑:
不修改__repr__和__str__的解决方案
def other_name(self, level=0):
print '\t' * level + repr(self.value)
for child in self.children:
child.other_name(level+1)
【问题讨论】:
标签: python python-2.7 printing tree