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

yipeiwu_com5年前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基于scipy实现信号滤波功能

Python基于scipy实现信号滤波功能

​ 1.背景介绍 在深度学习中,有时会使用Matlab进行滤波处理,再将处理过的数据送入神经网络中。这样是一般的处理方法,但是处理起来却有些繁琐,并且有时系统难以运行Matl...

Python使用pymysql小技巧

在使用pymysql的时候,通过fetchall()或fetchone()可以获得查询结果,但这个返回数据是不包含字段信息的(不如php方便)。查阅pymysql源代码后,其实获取查询结...

Python threading多线程编程实例

Python 的多线程有两种实现方法: 函数,线程类 1.函数 调用 thread 模块中的 start_new_thread() 函数来创建线程,以线程函数的形式告诉线程该做什么 复制...

Python with的用法

在Python中,with关键字是一个替你管理实现上下文协议对象的好东西。例如:file等。示例如下:    from __future__ import wi...

python+selenium 鼠标事件操作方法

一、前言 除了可以使用 click( ) 来模拟鼠标的单击操作,现在Web产品中还提供了更丰富的鼠标交互方式,例如鼠标右键、双击、悬停、拖动等功能,在WebDriver中,将这些关于鼠标...