评论数据的处理
我们可以取到的评论数据形式
comment_list=[ {"id":1,"content":"111","Pid":None}, {"id":2,"content":"222","Pid":None}, {"id":3,"content":"333","Pid":None}, {"id":4,"content":"444","Pid":1}, {"id":5,"content":"555","Pid":1}, {"id":6,"content":"666","Pid":4}, {"id":7,"content":"777","Pid":3}, {"id":8,"content":"888","Pid":7}, {"id":9,"content":"999","Pid":None}, ]
首先,给每条数据添加一个children_list(空列表)
for i in comment_list: i["children_list"] = []
得到新的列表
comment_list = [ {‘id‘: 1, ‘content‘: ‘111‘, ‘Pid‘: None, ‘children_list‘: []}, {‘id‘: 2, ‘content‘: ‘222‘, ‘Pid‘: None, ‘children_list‘: []}, {‘id‘: 3, ‘content‘: ‘333‘, ‘Pid‘: None, ‘children_list‘: []}, {‘id‘: 4, ‘content‘: ‘444‘, ‘Pid‘: 1, ‘children_list‘: []}, {‘id‘: 5, ‘content‘: ‘555‘, ‘Pid‘: 1, ‘children_list‘: []}, {‘id‘: 6, ‘content‘: ‘666‘, ‘Pid‘: 4, ‘children_list‘: []}, {‘id‘: 7, ‘content‘: ‘777‘, ‘Pid‘: 3, ‘children_list‘: []}, {‘id‘: 8, ‘content‘: ‘888‘, ‘Pid‘: 7, ‘children_list‘: []}, {‘id‘: 9, ‘content‘: ‘999‘, ‘Pid‘: None, ‘children_list‘: []} ]
然后通过变量引用的方法将子评论的内容加到对应的跟评论中
ret = [] for i in comment_list: if i["Pid"]: for j in comment_list: if j["id"] == i["Pid"]: j["children_list"].append(i) else: ret.append(i)
得到了我们需要的结果ret
ret = [ {‘id‘: 1, ‘content‘: ‘111‘, ‘Pid‘: None, ‘children_list‘: [{‘id‘: 4, ‘content‘: ‘444‘, ‘Pid‘: 1, ‘children_list‘: [{‘id‘: 6, ‘content‘: ‘666‘, ‘Pid‘: 4, ‘children_list‘: []}]}, {‘id‘: 5, ‘content‘: ‘555‘, ‘Pid‘: 1, ‘children_list‘: []}]}, {‘id‘: 2, ‘content‘: ‘222‘, ‘Pid‘: None, ‘children_list‘: []}, {‘id‘: 3, ‘content‘: ‘333‘, ‘Pid‘: None, ‘children_list‘: [{‘id‘: 7, ‘content‘: ‘777‘, ‘Pid‘: 3, ‘children_list‘: [{‘id‘: 8, ‘content‘: ‘888‘, ‘Pid‘: 7, ‘children_list‘: []}]}]}, {‘id‘: 9, ‘content‘: ‘999‘, ‘Pid‘: None, ‘children_list‘: []} ] # 结论:一旦某个数据引用了一个可变数据类型,这个可变数据类型发生变化,则这个数据也会发生变化