how to aggregate elements of a list of tuples if the tuples have the same first element?

后端 未结 4 736
日久生厌
日久生厌 2021-02-13 19:01

I have a list in which each value is a list of tuples. for example this is the value which I extract for a key :

     [(\'1998-01-20\',8) , (\'1998-01-22\',4) ,         


        
4条回答
  •  时光取名叫无心
    2021-02-13 19:19

    Try using itertools.groupby to aggregate values by month:

    from itertools import groupby
    a = [('1998-01-20', 8), ('1998-01-22', 4), ('1998-06-18', 8), 
         ('1999-07-15', 7), ('1999-07-21', 1)]
    
    for key, group in groupby(a, key=lambda x: x[0][:7]):
        print key, sum(j for i, j in group)
    
    # Output
    
    1998-01 12
    1998-06 8
    1999-07 8
    

    Here's a one-liner version:

    print [(key, sum(j for i, j in group)) for key, group in groupby(a, key=lambda x: x[0][:7])]
    
    # Output
    
    [('1998-01', 12), ('1998-06', 8), ('1999-07', 8)]
    

提交回复
热议问题