python - 在 Python 中打印树数据结构

标签 python python-2.7 printing tree

我正在寻找一种可能的树打印实现,它以用户友好的方式打印树,而不是作为对象的实例。

我在网上遇到了这个解决方案:

来源: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)

最佳答案

是的,将 __repr__ 代码移动到 __str__,然后在树上调用 str() 或将其传递给 print 语句。记得在递归调用中也使用 __str__:

class node(object):
    def __init__(self, value, children = []):
        self.value = value
        self.children = children

    def __str__(self, level=0):
        ret = "\t"*level+repr(self.value)+"\n"
        for child in self.children:
            ret += child.__str__(level+1)
        return ret

    def __repr__(self):
        return '<tree node representation>'

演示:

>>> root = node('grandmother')
>>> root.children = [node('daughter'), node('son')]
>>> root.children[0].children = [node('granddaughter'), node('grandson')]
>>> root.children[1].children = [node('granddaughter'), node('grandson')]
>>> root
<tree node representation>
>>> str(root)
"'grandmother'\n\t'daughter'\n\t\t'granddaughter'\n\t\t'grandson'\n\t'son'\n\t\t'granddaughter'\n\t\t'grandson'\n"
>>> print root
'grandmother'
    'daughter'
        'granddaughter'
        'grandson'
    'son'
        'granddaughter'
        'grandson'

关于python - 在 Python 中打印树数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20242479/

相关文章:

python-2.7 - python Psycopg删除不起作用

list - 将列表值枚举到字典列表中

python - 为什么python在time.sleep()之后不打印?

python - 使用 pandas dataframe 按时间顺序转换日期

python - 脚本没有阻塞

python - 如何规范化使用命名实体识别提取的关键字

python - 如何关联两个列表?

python | Pandas |对象 |转换为整数或 float

css - Google Chrome 打印分页符

python-3.x - 如何使用 Python 3 打印彩色输出?