第一种方法:把全部评论都一次列出来,需要用递归的方式实现:
class Node:
@staticmethod
def digui(ret, row):
for rt in ret:
if rt['id'] == row['parent_id']:
row['children'] = []
rt['children'].append(row)
return
else:
Node.digui(rt['children'],row)
@staticmethod
def create_tree(comment_list):
ret = []
for row in comment_list:
if not row['parent_id']: # None
row['children'] = []
ret.append(row)
else:
Node.digui(ret,row)
return ret
第二种方法:循环实现评论数据结构
前提:python中字典列表是引用类型,
举个栗子:因为列表li是引用类型,所以v和li引用同一个地址,v增加后li也同时增加,v删除后li也会删除