python3对list group by

作者:高景洋 日期:2020-12-03 16:07:44 浏览次数:670

from operator import itemgetter
from itertools import groupby


if __name__ == "__main__":
    
    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'))

    t = min(lst,key = itemgetter('age'))

    for key,group in lstg:
        for g in group: #group是一个迭代器,包含了所有的分组列表
            print('{} - {}'.format(key,g))


本文永久性链接:
<a href="http://r4.com.cn/art164.aspx">python3对list group by</a>
apple手机报价