首页 > 编程 > Python > 正文

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

2019-11-25 12:02:41
字体:
来源:转载
供稿:网友

项目:

基于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)的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表