Python使⽤groupby之字典分组
需求:根据列表中字段元素某个(些)字段分组
解决⽅案: functiontools中groupby函数进⾏分组,使⽤这个函数前必须先要排序,可通过使⽤operator 模块的itemgetter 函数,可以⾮常容易的排序这样的数据结构。
1 data=[
2
3 {'id': '078af4a6228047dba0' , 'main_code': 'TJ' , 'code': 'XC001' , ‘groupid’: 0 , 'column_name': 'name' , 'column_value': '张三'},
4
5 {'id': '078af4a6228047dba0' , 'main_code': 'TJ', 'code': 'XC001' , ‘groupid’: 0, 'column_name': 'age' , 'column_value': '27'},
6
7 {'id':'078af4a6228047dba0', 'main_code': 'TJ','code':'XC001',‘groupid’:1,'column_name':'name','column_value':'李四'},
groupby分组8
9 {'id':'078af4a6228047dba0', 'main_code': 'TJ','code':'XC001',‘groupid’:1,'column_name':'age','column_value':'45'},
10
11 {'id': '078af4a6228047dba0' , 'main_code': 'LP' , 'code': 'XC001' , ‘groupid’: 0 , 'column_name': 'name' , 'column_value': '张三'},
12
13 {'id': '078af4a6228047dba0' , 'main_code': 'LP', 'code': 'XC001' , ‘groupid’: 0, 'column_name': 'age' , 'column_value': '27'},
14
15 {'id':'078af4a6228047dba0', 'main_code': 'LP','code':'XC001',‘groupid’:1,'column_name':'name','column_value':'李四'},
16
17 {'id':'078af4a6228047dba0', 'main_code': 'LP','code':'XC001',‘groupid’:1,'column_name':'age','column_value':'45'},
18
19 {'id':'078af4a6228047dba0', 'main_code': 'TJ','code':'RY002',‘groupid’:0,'column_name':'sex','column_value':'男'},
20
21 {'id':'82970de3e3b836d34', 'main_code': 'TJ','code':'BD001',‘groupid’:0,'column_name':'isEnable','column_value':True}
22
23 ]
24
25from operator import itemgetter
26from itertools import groupby
27import json
28 data.sort(key=itemgetter('id'))
29 datas = []
30# id分组
31for id, items in groupby(data, key=itemgetter('id')):
32 data_dict = {'id': id}
33for code_info, item in groupby(items, key=itemgetter('main_code','code')):
34if code_info[0]:
35 column=[]
36 list_item=[i for i in item]
37 list_item.sort(key=itemgetter('groupid'))
38for group_id,g_item in groupby(list_item,key=itemgetter('groupid')):
39 column_dict = {}
40for gi in g_item:
41 column_('column_name')] = gi.get('column_value')
42 column_dict['group_id'] = group_id
43 column.append(column_dict)
44 data_dict[f'{code_info[0]}{code_info[1]}'] = column if len(column)>1 else column[0]
45else:
46 data_dict[f'{code_info[0]}{code_info[1]}'] = '⽆数据'
47 datas.append(data_dict)
48print(json.dumps(datas,ensure_ascii=False))
View Code
博友有其他⽅案,不吝赐教...
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论