Python中的字典分组函数(groupby,itertools)

Posted 梁颖

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python中的字典分组函数(groupby,itertools)相关的知识,希望对你有一定的参考价值。

 

from operator import itemgetter # itemgetter用来去dict中的key,省去了使用lambda函数
from itertools import groupby # itertool
d1={‘name‘:‘zhangsan‘,‘age‘:20,‘country‘:‘China‘}
d2={‘name‘:‘wangwu‘,‘age‘:19,‘country‘:‘USA‘}
d3={‘name‘:‘lisi‘,‘age‘:22,‘country‘:‘JP‘}
d4={‘name‘:‘zhaoliu‘,‘age‘:22,‘country‘:‘USA‘}
d5={‘name‘:‘pengqi‘,‘age‘:22,‘country‘:‘USA‘}
d6={‘name‘:‘lijiu‘,‘age‘:22,‘country‘:‘China‘}
lst=[d1,d2,d3,d4,d5,d6]

# 通过country进行分组:
lst.sort(key=itemgetter(‘country‘)) # 需要先排序,然后才能使用groupby
lstg = groupby(lst,itemgetter(‘country‘)) # 分组
# 等同于lstg = groupby(lst,key=lambda x:x[‘country‘])
for country,items in lstg:
    print(country)
    for item in items:
        print(item)

 

以上是关于Python中的字典分组函数(groupby,itertools)的主要内容,如果未能解决你的问题,请参考以下文章

Python数据分析分组统计groupby

Python中的groupby分组

Python中的字典分组和聚合列表

Python: 字典列表: 通过某个字段将记录分组

pandas使用groupby函数基于指定分组变量对dataframe数据进行分组使用agg函数计算每个分组不同数值变量的聚合统计值agg参数为字典指定不同变量的聚合计算统计量的形式

学不会的python之通过某几个关键字排序分组一个字典列表(列表中嵌套字典)