python简单模拟:把树存储在数据表中

在数据库中建立一个表,有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()

原文地址:https://www.cnblogs.com/wangfupeng1988/p/2014636.html