1. 程式人生 > >python簡單模擬:把樹存儲在數據表中

python簡單模擬:把樹存儲在數據表中

數據庫 __main__ __name__ com clas list lis 數據表 name

在數據庫中建立一個表,有Id, fatherId, value 三個字段,就可以存儲一個樹。

如何把該表中的數據以樹的形式呈現出來,下面小弟用python簡單模擬一下。

初學python,請大家多多指點。另外非常感謝http://www.cnblogs.com/lzyzizi/對小弟的指點。

運行結果:

技術分享
A-1
B-1
C-1
D-1
E-1
E-2
C-2
B-2
C-3
C-4
技術分享

源代碼:

技術分享
 1 #!user/bin/python
2
3 class noteModel:
4 def __init__(self,Id,value,fatherId):
5 self.Id=Id
6 self.value=value
7 self.fatherId=fatherId
8 self.children = []
9
10 def addChild(self,*child):
11 self.children += child
12
13 def printTree(self,layer):
14 print ‘ ‘*layer + self.value
15 map(lambda child:child.printTree(layer + 1), self.children)
16
17 def main():
18
19 #數據表模擬,數據庫有 Id, value, fatherId 三個字段,t1-t10代表10條數據行
20 t1 = noteModel(1,‘A-1‘,0)
21 t2 = noteModel(2,‘B-1‘,1)
22 t3 = noteModel(3,‘B-2‘,1)
23 t4 = noteModel(4,‘C-1‘,2)
24 t5 = noteModel(5,‘C-2‘,2)
25 t6 = noteModel(6,‘C-3‘,3)
26 t7 = noteModel(7,‘C-4‘,3)
27 t8 = noteModel(8,‘D-1‘,4)
28 t9 = noteModel(9,‘E-1‘,8)
29 t10 = noteModel(10,‘E-2‘,8)
30
31 #查詢數據庫,並生成列表
32 list = [t1,t2,t3,t4,t5,t6,t7,t8,t9,t10]
33
34 #循環列表,綁定父子關系,形成一個樹
35 for i in range(0, len(list)):
36 for j in range(0, len(list)):
37 if list[j].fatherId == list[i].Id:
38 list[i].addChild(list[j])
39
40 #打印樹
41 t1.printTree(0)
42
43 if __name__ == "__main__":
44 main()
技術分享

python簡單模擬:把樹存儲在數據表中