树形结构:首先是构造一种层级关系,主要用于层级菜单,或是一种递进的情况.
例:下面是一种层级关系,Pid字段后面的数字,指定的就是id数字的子层级.Pid等于None是根目录.
comment_list=[
{"id":1,"content":"...","Pid":None,"children_comments":[]},
{"id":2,"content":"...","Pid":None,"children_comments":[]},
{"id":3,"content":"...","Pid":None,"children_comments":[]},
{"id":4,"content":"...","Pid":1,"children_comments":[]},
{"id":5,"content":"...","Pid":1,"children_comments":[]},
{"id":6,"content":"...","Pid":4,"children_comments":[]},
{"id":7,"content":"...","Pid":3,"children_comments":[]},
{"id":8,"content":"...","Pid":7,"children_comments":[]},
{"id":9,"content":"...","Pid":None,"children_comments":[]},
]
首先把他们变成键值对,放在字典里.
comment_dict={}
for i in comment_list:
comment_list[i["id"]]=i #comment_dict的值就变成 ={1:{"id":1,"content":"...","Pid":None,"children_comments":[]},2:{"id":2,"content":"...","Pid":None,"children_comments":[]}...}
ret=[]
for comment in comment_list:
pid=comment['Pid']
if pid: #当pid字段不为空
comment_dict[pid]['children_comments'].append(comment) #pid值不为空,就是别人的子集,所以添加到相应父级的children_comments下.
else:
ret.append(comment) #把一些不要的数据取出来,
树形结构,利用的就是可变类型结构.
字典和列表类型,当你赋值给一个变量后,当在别的时候变化,他原来的代码也会跟着改变.