栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Python中打印Tree数据结构

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Python中打印Tree数据结构

是的,将

__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'nt'daughter'ntt'granddaughter'ntt'grandson'nt'son'ntt'granddaughter'ntt'grandson'n">>> print root'grandmother'    'daughter'        'granddaughter'        'grandson'    'son'        'granddaughter'        'grandson'


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/653271.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号