首页 > 代码库 > 报障系统之多级评论前戏
报障系统之多级评论前戏
前戏:
- 列表添加:列表添加元素练习
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‘]] = itemresult = []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循环亦可以实现,但是效率较低。
知识扩展:
算法练习
报障系统之多级评论前戏
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。