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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值