字典传递的是应用,后面的对字典的操作,会更新到前面的收据中,与评论类似的的有,商城项目中的商品类别洒基分类的问题
#把father_comment_id为NULL的筛选出来,father_comment_id为None的说明是根评论(对文章的评论),有值就是子评论(对评论的评论)
comment_list=[
{'id': 154, 'content': '发个', 'farther_comment_id': None},
{'id': 155, 'content': '你好啊', 'farther_comment_id': None},
{'id': 156, 'content': '嘻嘻', 'farther_comment_id': 155},
{'id': 157, 'content': '哎呦', 'farther_comment_id': 156},
{'id': 158, 'content': '不错。继续加油', 'farther_comment_id': None},
{'id': 159, 'content': '运往直前', 'farther_comment_id': None},
{'id': 160, 'content': '加油啦', 'farther_comment_id': 159},
{'id': 161, 'content': '爱你啊', 'farther_comment_id': 159},
{'id': 162, 'content': '@undefined\n的说的得分是', 'farther_comment_id': None}
]
一开始查到的所有的评论是这样的列表,我们需要把这些数据构建一下,方便处理
# ===========放一个字典,吧id提出来,并且在每一个字典中加一个"children_comment":[]键值对==========
comment_dict = {}
for comment in comment_list:
comment["children_comment"] = []
comment_dict[comment["id"]]=comment
# print(comment_dict) #{1:{"":"","":""},2:{"":"","":""},3:{}}
# 将comment_list转换为以评论的id为key的comment_dict
{
154: {'id': 154, 'content': '发个', 'farther_comment_id': None, 'children_comment': []},
155: {'id': 155, 'content': '你好啊', 'farther_comment_id': None, 'children_comment': []},
156: {'id': 156, 'content': '嘻嘻', 'farther_comment_id': 155, 'children_comment': []},
157: {'id': 157, 'content': '哎呦', 'farther_comment_id': 156, 'children_comment': []},
158: {'id': 158, 'content': '不错。继续加油', 'farther_comment_id': None, 'children_comment': []},
159: {'id': 159, 'content': '运往直前', 'farther_comment_id': None, 'children_comment': []},
160: {'id': 160, 'content': '加油啦', 'farther_comment_id': 159, 'children_comment': []},
161: {'id': 161, 'content': '爱你啊', 'farther_comment_id': 159, 'children_comment': []},
162: {'id': 162, 'content': '@undefined\n的说的得分是', 'farther_comment_id': None, 'children_comment': []}
}
找farther_comment_id为none的存放起来
comment_tree=[]
for comment in comment_list:
pid = comment["farther_comment_id"]
if pid: #如果有值就找到对应的pid添加到children_comment列表中
comment_dict[pid]["children_comment"].append(comment)
else:
'''如果pid为none的时候找一个列表存起来'''
comment_tree.append(comment)
print(comment_tree)
最后拿到的comment_tree是这样的
comment_tree:
[
{
'id': 154,
'content': '发个',
'farther_comment_id': None,
'children_comment': [
]
},
{
'id': 155,
'content': '你好啊',
'farther_comment_id': None,
'children_comment': [
{
'id': 156,
'content': '嘻嘻',
'farther_comment_id': 155,
'children_comment': [
{
'id': 157,
'content': '哎呦',
'farther_comment_id': 156,
'children_comment': [
]
}
]
}
]
},
{
'id': 158,
'content': '不错。继续加油',
'farther_comment_id': None,
'children_comment': []
},
{
'id': 159,
'content': '运往直前',
'farther_comment_id': None,
'children_comment': [
{
'id': 160,
'content': '加油啦',
'farther_comment_id': 159,
'children_comment': [
]
},
{
'id': 161,
'content': '爱你啊',
'farther_comment_id': 159,
'children_comment': [
]
}
]
},
{
'id': 162,
'content': '@undefined\n的说的得分是',
'farther_comment_id': None,
'children_comment': [
]
}
]