前戏:
- 列表添加:
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循环亦可以实现,但是效率较低。
知识扩展:
时间: 2024-10-12 13:14:51