報障系統之多級評論前戲
阿新 • • 發佈:2017-07-17
true none _id bsp nbsp 多級 append clas tco
前戲:
- 列表添加:
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]], # [
列表添加元素練習 - 字典添加:
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循環亦可以實現,但是效率較低。
知識擴展:
算法練習
報障系統之多級評論前戲