标签:需要 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‘}]} ‘‘‘
标签:需要 group .so for iter int print 列表 rom
原文地址:https://www.cnblogs.com/st-st/p/9676756.html