利用循环实现评论数据结构

#_author:来童星
#date:2020/4/19
#循环实现评论数据结构
comment_list=[
{"id":1,"content":"python最厉害","user":"来星星","parent_id":None},
{"id":2,"content":"GO最厉害","user":"来星星","parent_id":None},
{"id":3,"content":"C++最厉害","user":"来星星","parent_id":None},
{"id":4,"content":"你最厉害","user":"琪琪","parent_id":1},
{"id":5,"content":"老师最厉害","user":"娜娜","parent_id":1},
{"id":6,"content":"吴建华厉害","user":"吴建华","parent_id":4},
{"id":7,"content":"心悦最厉害","user":"心悦","parent_id":2},
{"id":8,"content":"心悦最帅","user":"心悦","parent_id":3},
{"id":9,"content":"好好好,心悦最帅公认的","user":"来星星","parent_id":8},

]
ret=[]

comment_list_dict={}
for row in comment_list:
row.update({'children':[]})
comment_list_dict[row['id']]=row



for item in comment_list:

parent_row=comment_list_dict.get(item['parent_id'])
if not parent_row:
ret.append(item)
else:
parent_row['children'].append(item)
print(ret)


运行结果:


[{
'id': 1,
'parent_id': None,
'user': '来星星',
'content': 'python最厉害',
'children': [{
'id': 4,
'parent_id': 1,
'user': '琪琪',
'content': '你最厉害',
'children': [{
'id': 6,
'parent_id': 4,
'user': '吴建华',
'content': '吴建华厉害',
'children': []
}]
}, {
'id': 5,
'parent_id': 1,
'user': '娜娜',
'content': '老师最厉害',
'children': []
}]
}, {
'id': 2,
'parent_id': None,
'user': '来星星',
'content': 'GO最厉害',
'children': [{
'id': 7,
'parent_id': 2,
'user': '心悦',
'content': '心悦最厉害',
'children': []
}]
}, {
'id': 3,
'parent_id': None,
'user': '来星星',
'content': 'C++最厉害',
'children': [{
'id': 8,
'parent_id': 3,
'user': '心悦',
'content': '心悦最帅',
'children': [{
'id': 9,
'parent_id': 8,
'user': '来星星',
'content': '好好好,心悦最帅公认的',
'children': []
}]
}]
}]


comment_list_dict中的数据结构:

{
1: {
'children': [],
'user': '来星星',
'id': 1,
'content': 'python最厉害',
'parent_id': None
},
2: {
'children': [],
'user': '来星星',
'id': 2,
'content': 'GO最厉害',
'parent_id': None
},
3: {
'children': [],
'user': '来星星',
'id': 3,
'content': 'C++最厉害',
'parent_id': None
},
4: {
'children': [],
'user': '琪琪',
'id': 4,
'content': '你最厉害',
'parent_id': 1
},
5: {
'children': [],
'user': '娜娜',
'id': 5,
'content': '老师最厉害',
'parent_id': 1
},
6: {
'children': [],
'user': '吴建华',
'id': 6,
'content': '吴建华厉害',
'parent_id': 4
},
7: {
'children': [],
'user': '心悦',
'id': 7,
'content': '心悦最厉害',
'parent_id': 2
},
8: {
'children': [],
'user': '心悦',
'id': 8,
'content': '心悦最帅',
'parent_id': 3
},
9: {
'children': [],
'user': '来星星',
'id': 9,
'content': '好好好,心悦最帅公认的',
'parent_id': 8
}
}

posted @ 2020-04-19 22:26  Stary_tx  阅读(324)  评论(0编辑  收藏  举报