2020-04-04-python函数迭代器

itertools.groupby函数,对dic类型的值进行分组,但谨记,分组前需要排序
方法一:
对元组分组:

import itertools
from operator import itemgetter

lst_data = [(1, 2), (2, 3), (1, 4), (5, 5), (3, 4), (2, 6)]
# soo = sorted(lst_data, key=itemgetter(0))
soo = sorted(lst_data, key=lambda x: x[0])
ss = itertools.groupby(soo, key=itemgetter(0))
for k, v in ss:
    print(k, [i for i in v])
#######################################
# 输出:
1 [(1, 2), (1, 4)]
2 [(2, 3), (2, 6)]
3 [(3, 4)]
5 [(5, 5)]

Process finished with exit code 0

方法二,对字典分组:

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_dic = [d1, d2, d3, d4, d5, d6]
lst_dicso = sorted(lst_dic, key=itemgetter('country')) # 排序
#lst_dicso = sorted(lst_dic, key = lambda x : x['country'])  # 排序
group_dicso = itertools.groupby(lst_dicso,key=itemgetter('country')) # 分组
for k,v in group_dicso:
    print(k, [i for i in v])

############################################################
# 输出:
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'}]

Process finished with exit code 0

【注意】

itemgetter函数用于指定获取迭代对象中的哪些维度的数据;或者可以用来指定迭代器排序的域,等价于lambda表达式。

你可能感兴趣的:(2020-04-04-python函数迭代器)