当前位置: 首页 > 工具软件 > tootgroup.py > 使用案例 >

python itertools groupby 以及itemgetter 使用

赏梓
2023-12-01
from operator import itemgetter
from itertools import groupby

源数据为这样


_ = [
{'conf_id': 4, 'username': '.zhang'}, 
{'conf_id': 10, 'username': '.zhang'}, 
{'conf_id': 4, 'username': '.wang'}, 
{'conf_id': 17, 'username': '.zhang'}
]

想根据conf_id 分组
首先需要根据conf_id排序

_.sort(key=itemgetter('conf_id'))
[
 {'conf_id': 4, 'username': '.zhang'}, 
 {'conf_id': 4, 'username': '.wang'},
 {'conf_id': 10, 'username': '.zhang'}, 
 {'conf_id': 17, 'username': '.zhang'}
 ]

 for conf_id, obj in groupby(_, key=itemgetter('conf_id')):
     print(conf_id, obj)
4 <itertools._grouper object at 0x000002B56E648B08>
10 <itertools._grouper object at 0x000002B56E6D55C8>
17 <itertools._grouper object at 0x000002B56E6D5988>

obj可以转成list方便查看

    for conf_id, obj in groupby(_, key=itemgetter('conf_id')):
        print(conf_id, list(obj))
4 [{'conf_id': 4, 'username': '.zhang'}, {'conf_id': 4, 'username': '.wang'}]
10 [{'conf_id': 10, 'username': '.zhang'}]
17 [{'conf_id': 17, 'username': '.zhang'}]

 类似资料: