Python多叉树的构造及取出节点数据(treelib)的方法

yipeiwu_com6年前Python基础

项目:

基于Pymysql的专家随机抽取系统

引入库函数:

>>> import treelib
>>> from treelib import Tree, Node

构造节点类:

>>> class Nodex(object): \
    def __init__(self, num): \
      self.num = num

构造多叉树:(注意节点的第2个属性已标红,它是节点ID,为str类型,不能与其他节点重复,否则构建节点失败)

>>> tree1 = Tree()
>>> tree1.create_node('Root', 'root', data = Nodex('3'));\
   tree1.create_node('Child1', 'child1', parent = 'root', data =Nodex('4'));\
   tree1.create_node('Child2', 'child2', parent = 'root', data =Nodex('5'));\
   tree1.create_node('Child3', 'child3', parent = 'root', data =Nodex('6'));\

构造结果:

>>> tree1.show()
Root
├── Child1
├── Child2
└── Child3

>>> tree1.show(data_property = 'num')
3
├── 4
├── 5
└── 6

打印节点信息:(其实节点是以字典的形式存储的)

>>> tree1.nodes
{'root': Node(tag=Root, identifier=root, data=<__main__.Nodex object at 0x000002265C6A9550>), 'child1': Node(tag=Child1, identifier=child1, data=<__main__.Nodex object at 0x000002265C6A9E10>)}

取出child1节点存储的数据:

>>> tree1.nodes['child1'].data.num
'4'

以上这篇Python多叉树的构造及取出节点数据(treelib)的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python函数的5种参数详解

(1)       位置参数,调用函数时按位置传入参数 (2)     &n...

详解Python logging调用Logger.info方法的处理过程

详解Python logging调用Logger.info方法的处理过程

本次分析一下Logger.info的流程 1. Logger.info源码: def info(self, msg, *args, **kwargs): """ Log...

Python之PyUnit单元测试实例

本文实例讲述了Python之PyUnit单元测试,与erlang eunit单元测试很像,分享给大家供大家参考。具体方法如下: 1.widget.py文件如下: 复制代码 代码如下:#!...

python九九乘法表的实例

python九九乘法表的实例

python2.7 for i in range(1,10): for j in range(1,i+1): print j,'x',i,'=',j*i,'\t', prin...

Python中AND、OR的一个使用小技巧

python中的and-or可以用来当作c用的?:用法。比如 1 and a or b,但是需要确保a为True,否则a为False,还要继续判断b的值,最后打印b的值。 今天看到一个好...