当前位置:主页 > 软件编程 > Python代码 >

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

时间:2021-05-08 09:05:49 | 栏目: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'

您可能感兴趣的文章:

相关文章