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中的rjust()方法使用详解

 rjust()该方法返回字符串合理字符串的右边的长度宽度。填充是通过使用指定的fillchar(默认为空格)。如果宽度小于len(s)返回原始字符串。 语法 以下是rjust...

对python Tkinter Text的用法详解

1.设置python Tkinter Text控件文本的方法 text.insert(index,string)  index = x.y的形式,x表示行,y表示列 向第一行插...

Python3 中把txt数据文件读入到矩阵中的方法

1.实例程序: ''' 数据文件:2.txt内容:(以空格分开每个数据) 1 2 2.5 3 4 4 7 8 7 ''' from numpy import * A = zeros...

Python实现类继承实例

Python是一种解释型、面向对象、动态数据类型的高级程序设计语言,本文就举一例Python类继承的实例。 实例代码如下: #! /usr/bin/python # Filenam...

Python实现进程同步和通信的方法

Python中的多线程其实并不是真正的多线程,如果想要充分地使用多核CPU的资源,在python中大部分情况需要使用多进程。Python提供了非常好用的多进程包multiprocessi...