Python多叉樹的構(gòu)造及取出節(jié)點數(shù)據(jù)(treelib)的方法
項目:
基于Pymysql的專家隨機抽取系統(tǒng)
引入庫函數(shù):
>>> import treelib >>> from treelib import Tree, Node
構(gòu)造節(jié)點類:
>>> class Nodex(object): \ def __init__(self, num): \ self.num = num
構(gòu)造多叉樹:(注意節(jié)點的第2個屬性已標紅,它是節(jié)點ID,為str類型,不能與其他節(jié)點重復(fù),否則構(gòu)建節(jié)點失?。?/p>
>>> 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é)點信息:(其實節(jié)點是以字典的形式存儲的)
>>> 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é)點存儲的數(shù)據(jù):
>>> tree1.nodes['child1'].data.num '4'
以上這篇Python多叉樹的構(gòu)造及取出節(jié)點數(shù)據(jù)(treelib)的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
pycharm 使用心得(九)解決No Python interpreter selected的問題
PyCharm 是由JetBrains打造的一款 Python IDE。具有智能代碼編輯器,能理解 Python 的特性并提供卓越的生產(chǎn)力推進工具:自動代碼格式化、代碼完成、重構(gòu)、自動導(dǎo)入和一鍵代碼導(dǎo)航等。這些功能在先進代碼分析程序的支持下,使 PyCharm 成為 Python 專業(yè)開發(fā)人員和剛起步人員使用的有力工具。2014-06-06