码迷,mamicode.com
首页 > 其他好文 > 详细

分组函数(groupby、itemgetter)

时间:2018-09-19 21:52:58      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:需要   group   .so   for   iter   int   print   列表   rom   

from itertools import groupby
from operator import itemgetter

d1={name:liuyi,age:25,city:SZ}
d2={name:chener,age:18,city:SH}
d3={name:zhangsan,age:23,city:GZ}
d4={name:lisi,age:24,city:HZ}
d5={name:wangwu,age:22,city:BJ}
d6={name:zhangliu,age:21,city:WH}
lis = [d1,d2,d3,d4,d5,d6]

lis.sort(key=itemgetter(city))        # 使用groupby需要先排序

lst_grou = groupby(lis,itemgetter(city))  # itemgetter(‘city‘) 相当于 key = lambda x:x[‘city‘]
for key,group in lst_grou:                  # group 使一个迭代器,包含了所有的分组
    for g in group:
        print(key,g)
        
‘‘‘
结果
BJ {‘name‘: ‘wangwu‘, ‘age‘: 22, ‘city‘: ‘BJ‘}
GZ {‘name‘: ‘zhangsan‘, ‘age‘: 23, ‘city‘: ‘GZ‘}
HZ {‘name‘: ‘lisi‘, ‘age‘: 24, ‘city‘: ‘HZ‘}
SH {‘name‘: ‘chener‘, ‘age‘: 18, ‘city‘: ‘SH‘}
SZ {‘name‘: ‘liuyi‘, ‘age‘: 25, ‘city‘: ‘SZ‘}
WH {‘name‘: ‘zhangliu‘, ‘age‘: 21, ‘city‘: ‘WH‘}
‘‘‘
from itertools import groupby
from operator import itemgetter

d1={name:liuyi,age:25,city:SZ}
d2={name:chener,age:18,city:SH}
d3={name:zhangsan,age:23,city:GZ}
d4={name:lisi,age:24,city:SZ}
d5={name:wangwu,age:22,city:BJ}
d6={name:zhangliu,age:21,city:WH}
lis = [d1,d2,d3,d4,d5,d6]

lis.sort(key=itemgetter(city))        # 使用groupby需要先排序

lst_grou = groupby(lis,itemgetter(city))  # itemgetter(‘city‘) 相当于 key = lambda x:x[‘city]
print([key for key,group in lst_grou])      # 列表推导式,会自动去重

‘‘‘
结果
[‘BJ‘, ‘GZ‘, ‘SH‘, ‘SZ‘, ‘WH‘]
‘‘‘
print(dict([(key,list(group)) for key,group in lst_grou]))  # 获取字典

‘‘‘
结果
{‘BJ‘: [{‘name‘: ‘wangwu‘, ‘age‘: 22, ‘city‘: ‘BJ‘}], 
‘GZ‘: [{‘name‘: ‘zhangsan‘, ‘age‘: 23, ‘city‘: ‘GZ‘}], 
‘SH‘: [{‘name‘: ‘chener‘, ‘age‘: 18, ‘city‘: ‘SH‘}], 
‘SZ‘: [{‘name‘: ‘liuyi‘, ‘age‘: 25, ‘city‘: ‘SZ‘}, {‘name‘: ‘lisi‘, ‘age‘: 24, ‘city‘: ‘SZ‘}], 
‘WH‘: [{‘name‘: ‘zhangliu‘, ‘age‘: 21, ‘city‘: ‘WH‘}]}
‘‘‘

 

分组函数(groupby、itemgetter)

标签:需要   group   .so   for   iter   int   print   列表   rom   

原文地址:https://www.cnblogs.com/st-st/p/9676756.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!