groupby()把迭代器中相邻的,指定特征重复的元素挑出来放在一起
from operator import itemgetter #itemgetter用来取dict中的key,省去了使用lambda函数
from itertools import groupby
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]
lst.sort(key=itemgetter('country')) #先排序,再进行groupby。lst排序后自身被改变
lstg = groupby(lst,itemgetter('country'))
#lstg = groupby(lst,key=lambda x:x['country']) 等同于使用itemgetter()
for key,group in lstg:
print(key,list(group))
#返回:
China [{'name': 'zhangsan', 'age': 20, 'country': 'China'}, {'name': 'lijiu', 'age': 22, 'country': 'China'}]
JP [{'name': 'lisi', 'age': 22, 'country': 'JP'}]
USA [{'name': 'wangwu', 'age': 19, 'country': 'USA'}, {'name': 'zhaoliu', 'age': 22, 'country': 'USA'}, {'name': 'pengqi', 'age': 22, 'country': 'USA'}]
import itertools
def height_class(h):
if h>180:
return 'tall'
elif h<160:
return 'short'
else:
return 'middle'
friends = [191, 158, 159, 165, 170, 177, 181, 182, 190]
for m,n in itertools.groupby(friends,key = height_class):
print(m,list(n))
#返回:
tall [191]
short [158, 159]
middle [165, 170, 177]
tall [181, 182, 190]
由于191与181,182,190不相邻,因此分组结果不在一组。
import itertools
def height_class(h):
if h>180:
return 'tall'
elif h<160:
return 'short'
else:
return 'middle'
friends = [191, 158, 159, 165, 170, 177, 181, 182, 190]
friends = sorted(friends,key = height_class)
for m,n in itertools.groupby(friends,key = height_class):
print(m,list(n))
#返回:
middle [165, 170, 177]
short [158, 159]
tall [191, 181, 182, 190]