fromoperatorImportItemgetter#Itemgetter used to go to the key in Dict, eliminating the use of lambda functions fromItertoolsImportGroupBy#Itertool also contains a number of other functions, such as combining multiple lists together. 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]#to GROUP by country:Lst.sort (Key=itemgetter ('Country'))#you need to sort before you can groupby. LST sort itself is changedLSTG = GroupBy (Lst,itemgetter ('Country')) #Lstg = groupby (lst,key=lambda x:x[' country ') is equivalent to using Itemgetter ()
forKey,groupinchLSTG: forGinchGroup#Group is an iterator that contains all the grouped lists Printkey,g return: China {'Country':' China',' Age': 20,'name':'Zhangsan'}china {'Country':' China',' Age': 22,'name':'Lijiu'}JP {'Country':'JP',' Age': 22,'name':'Lisi'}usa {'Country':'USA',' Age': 19,'name':'Wangwu'}usa {'Country':'USA',' Age': 22,'name':'Zhaoliu'}usa {'Country':'USA',' Age': 22,'name':'Pengqi'}Print[Key forKey,groupinchLSTG]#return: [' China ', ' JP ', ' USA ']Print[(Key,list (group)) forKey,groupinchLstg]#The returned list contains three tuples:[(' China', [{'Country':' China',' Age': 20,'name':'Zhangsan'}, {'Country':' China',' Age': 22,'name':'Lijiu'}]), ('JP', [{'Country':'JP',' Age': 22,'name':'Lisi'}]), ('USA', [{'Country':'USA',' Age': 19,'name':'Wangwu'}, {'Country':'USA',' Age': 22,'name':'Zhaoliu'}, {'Country':'USA',' Age': 22,'name':'Pengqi'}])]PrintDict ([Key,list (group)) forKey,groupinchLstg])#The return is a dictionary:{'JP': [{'Country':'JP',' Age': 22,'name':'Lisi'}],' China': [{'Country':' China',' Age': 20,'name':'Zhangsan'}, {'Country':' China',' Age': 22,'name':'Lijiu'}],'USA': [{'Country':'USA',' Age': 19,'name':'Wangwu'}, {'Country':'USA',' Age': 22,'name':'Zhaoliu'}, {'Country':'USA',' Age': 22,'name':'Pengqi'}]}PrintDict ([Key,len (group)) forKey,groupinchLstg])#returns the number of each grouping:{'JP': 1,' China': 2,'USA': 3}
# Returns a group that contains more than 2 elements Print for in GroupBy (sorted (Lst,key=itemgetter ('country')), Itemgetter (' Country'if len (List (group)) >=2]# return: [' China ', ' USA ']
grouping functions in Python (GroupBy, Itertools)