Python simple simulation: storing a tree in a data table

Source: Internet
Author: User
Tags addchild

Create a table in the database, with ID, Fatherid, value three fields, you can store a tree.

How to put the table data in the form of a tree, the following little brother with Python simple simulation.

Beginner python, please give us a lot of advice. In addition very grateful http://www.cnblogs.com/lzyzizi/to younger brother's guidance.

Operation Result:

A-1
B-1
C-1
D-1
E-1
E-2
C-2
B-2
C-3
C-4

Source:

1 #!user/bin/python
2  
3  classNotemodel:
4 def__init__(Self,id,value,fatherid):
5 Self . Id=Id
6 Self.value=value
7 Self.fatherid=Fatherid
8 Self.children= []
9
Ten defAddChild (self,*Child ):
One Self.children+=Child
A
- defPrinttree (Self,layer):
- Print''*Layer+Self.value
the Map (Lambdachild:child.printTree (Layer+1), Self.children)
-
-  defMain ():
-
+ #data table simulation, database has Id, value, Fatherid three fields, t1-t10 represents 10 rows of data
-  T1=Notemodel (1,'A-1', 0)
+ T2=Notemodel (2,'B-1',1)
A T3=Notemodel (3,'B-2',1)
at T4=Notemodel (4,'C-1',2)
- T5=Notemodel (5,'C-2',2)
- T6=Notemodel (6,'C-3',3)
- T7=Notemodel (7,'C-4',3)
- T8=Notemodel (8,'D-1',4)
- T9=Notemodel (9,'E-1',8)
in T10=Notemodel (Ten,'E-2',8)
-
to #querying the database and generating the list
+ List=[T1,t2,t3,t4,t5,t6,t7,t8,t9,t10]
-
the #looping lists, binding parent-child relationships, forming a tree
* forIinchRange (0, Len (list)):
$ forJinchRange (0, Len (list)):
Panax Notoginseng ifList[j].fatherid==List[i]. Id:
- List[i].addchild (List[j])
the
+ #Print Tree
A t1.printtree (0)
the
+ if__name__=="__main__":
- Main ()

Python simple simulation: storing a tree in a data table

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.