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

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

    Just use defaultdict:

    from collections import defaultdict
    
    
    DATA = [
        ('1998-01-20', 8),
        ('1998-01-22', 4),
        ('1998-06-18', 8),
        ('1999-07-15', 7),
        ('1999-07-21', 1),
    ]
    
    
    groups = defaultdict(int)
    for date, value in DATA:
        groups[date[:7]] += value
    
    
    from pprint import pprint
    pprint(groups)
    

提交回复
热议问题