报障系统之多级评论前戏
Posted luchuangao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了报障系统之多级评论前戏相关的知识,希望对你有一定的参考价值。
前戏:
- 列表添加:
v1 = [1,2,3,4] v1.append(123) print(v1) data = [ [11,22,33], [44,55,66] ] data[0].append(data[1]) print(data) # data = [ # [11,22,33, [44,55,66]], # [44,55,66] # ] data[1].append(77) print(data) # data = [ # [11,22,33, [44,55,66,77]], # [44,55,66,77] # ] print(data[0][3]) #[44, 55, 66, 77]
- 字典添加:
v1 = {‘k1‘:‘v1‘} v1[‘k2‘] = ‘v2‘ print(v1) data = [ {‘k1‘:‘v1‘}, {‘k2‘:‘v2‘} ] for item in data: item[‘kk‘] = ‘vv‘ print(data)
案例:
如果parent_id非0,并且parent_id等于id 就添加到id值相同得那行:
# msg_list = [
# {‘id‘:1,‘content‘:‘xxx‘,‘parent_id‘:None},
# {‘id‘:2,‘content‘:‘xxx‘,‘parent_id‘:None},
# {‘id‘:3,‘content‘:‘xxx‘,‘parent_id‘:None},
# {‘id‘:4,‘content‘:‘xxx‘,‘parent_id‘:1},
# {‘id‘:5,‘content‘:‘xxx‘,‘parent_id‘:4},
# {‘id‘:6,‘content‘:‘xxx‘,‘parent_id‘:2},
# {‘id‘:7,‘content‘:‘xxx‘,‘parent_id‘:5},
# {‘id‘:8,‘content‘:‘xxx‘,‘parent_id‘:3},
# ]
"""
msg_list = [
{
‘id‘:1,‘content‘:‘xxx‘,parent_id:None,child:[
{‘id‘:4,‘content‘:‘xxx‘,parent_id:1},
{‘id‘:5,‘content‘:‘xxx‘,parent_id:1,child:[
{‘id‘:7,‘content‘:‘xxx‘,parent_id:5},
]}]
},
{‘id‘:2,‘content‘:‘xxx‘,parent_id:None,child:[
{‘id‘:6,‘content‘:‘xxx‘,parent_id:2},
]},
{‘id‘:3,‘content‘:‘xxx‘,parent_id:None,child:[
{‘id‘:8,‘content‘:‘xxx‘,parent_id:3},
]},
]
"""
案例代码:
msg_list = [ {‘id‘:1,‘content‘:‘xxx‘,‘parent_id‘:None}, {‘id‘:2,‘content‘:‘xxx‘,‘parent_id‘:None}, {‘id‘:3,‘content‘:‘xxx‘,‘parent_id‘:None}, {‘id‘:4,‘content‘:‘xxx‘,‘parent_id‘:1}, {‘id‘:5,‘content‘:‘xxx‘,‘parent_id‘:4}, {‘id‘:6,‘content‘:‘xxx‘,‘parent_id‘:2}, {‘id‘:7,‘content‘:‘xxx‘,‘parent_id‘:5}, {‘id‘:8,‘content‘:‘xxx‘,‘parent_id‘:3}, ] # v = [ row.setdefault(‘child‘,[]) for row in msg_list] # 列表生成式 msg_list_dict = { } for item in msg_list: item[‘child‘]=[] msg_list_dict[item[‘id‘]] = item result = [] for item in msg_list: pid = item[‘parent_id‘] if pid: msg_list_dict[pid][‘child‘].append(item) else: result.append(item) for i in result: print(i)
解题思路:
- 通过冒泡算法进行解答。【推荐】
- 通过for嵌套for循环亦可以实现,但是效率较低。
知识扩展:
以上是关于报障系统之多级评论前戏的主要内容,如果未能解决你的问题,请参考以下文章