項(xiàng)目:
基于Pymysql的專家隨機(jī)抽取系統(tǒng)
引入庫函數(shù):
>>> import treelib
>>> from treelib import Tree, Node
構(gòu)造節(jié)點(diǎn)類:
>>> class Nodex(object): \
def __init__(self, num): \
self.num = num
構(gòu)造多叉樹: (注意節(jié)點(diǎn)的第2個(gè)屬性已標(biāo)紅,它是節(jié)點(diǎn)ID,為str類型,不能與其他節(jié)點(diǎn)重復(fù),否則構(gòu)建節(jié)點(diǎn)失敗)
>>> 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'));\
構(gòu)造結(jié)果:
>>> tree1.show()
Root
├── Child1
├── Child2
└── Child3
>>> tree1.show(data_property = 'num')
3
├── 4
├── 5
└── 6
打印節(jié)點(diǎn)信息:(其實(shí)節(jié)點(diǎn)是以字典的形式存儲的)
>>> 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節(jié)點(diǎn)存儲的數(shù)據(jù):
>>> tree1.nodes['child1'].data.num
'4'
以上這篇Python多叉樹的構(gòu)造及取出節(jié)點(diǎn)數(shù)據(jù)(treelib)的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

