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

后端 未结 4 727
日久生厌
日久生厌 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:08

    I like to use defaultdict for counting:

    from collections import defaultdict
    
    lst = [('1998-01-20',8) , ('1998-01-22',4) , ('1998-06-18',8 ) , ('1999-07-15' , 7), ('1999-07-21',1)]
    
    result = defaultdict(int)
    
    for date, cnt in lst:
        year, month, day = date.split('-')
        result['-'.join([year, month])] += cnt
    
    print(result)
    

提交回复
热议问题