首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Python中打印树数据结构

在Python中打印树数据结构
EN

Stack Overflow用户
提问于 2013-11-27 20:25:50
回答 2查看 69.1K关注 0票数 24

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

我在网上发现了这个解决方案:

来源:http://cbio.ufs.ac.za/live_docs/nbn_tut/trees.html

代码语言:javascript
复制
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

此代码以以下方式打印树:

代码语言:javascript
复制
'grandmother'
    'daughter'
        'granddaughter'
        'grandson'
    'son'
        'granddaughter'
        'grandson'

有没有可能在不更改__repr__方法的情况下得到相同的结果,因为我正在将它用于另一个目的。

编辑:

无需修改__repr____str__的解决方案

代码语言:javascript
复制
def other_name(self, level=0):
    print '\t' * level + repr(self.value)
    for child in self.children:
        child.other_name(level+1)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-27 20:26:45

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

代码语言:javascript
复制
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>'

演示:

代码语言:javascript
复制
>>> 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'
票数 34
EN

Stack Overflow用户

发布于 2016-09-27 20:27:19

为什么不将其存储为treelib object并将其打印出来,就像我们打印CHAID树输出here一样,其中包含与您的用例相关的更多相关节点描述?

代码语言:javascript
复制
([], {0: 809, 1: 500}, (sex, p=1.47145310169e-81, chi=365.886947811, groups=[['female'], ['male']]))
├── (['female'], {0: 127, 1: 339}, (embarked, p=9.17624191599e-07, chi=24.0936494474, groups=[['C', '<missing>'], ['Q', 'S']]))
│   ├── (['C', '<missing>'], {0: 11, 1: 104}, <Invalid Chaid Split>)
│   └── (['Q', 'S'], {0: 116, 1: 235}, <Invalid Chaid Split>)
└── (['male'], {0: 682, 1: 161}, (embarked, p=5.017855245e-05, chi=16.4413525404, groups=[['C'], ['Q', 'S']]))
    ├── (['C'], {0: 109, 1: 48}, <Invalid Chaid Split>)
    └── (['Q', 'S'], {0: 573, 1: 113}, <Invalid Chaid Split>)
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20242479

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档