Python中的字典分組函數(groupby,itertools)


 

from operator import itemgetter # itemgetter用來去dict中的key,省去了使用lambda函數
from itertools import groupby # itertool
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] # 通過country進行分組: lst.sort(key=itemgetter('country')) # 需要先排序,然后才能使用groupby lstg = groupby(lst,itemgetter('country')) # 分組 # 等同於lstg = groupby(lst,key=lambda x:x['country']) for country,items in lstg: print(country) for item in items: print(item)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM