django-樹形結構

 

樹形結構:首先是構造一種層級關係,主要用於層級菜單,或是一種遞進的狀況.

例:下面是一種層級關係,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)          #把一些不要的數據取出來, 樹形結構,利用的就是可變類型結構.字典和列表類型,當你賦值給一個變量後,當在別的時候變化,他原來的代碼也會跟着改變.
相關文章
相關標籤/搜索