Summing values in nested list when item changes

后端 未结 5 1167
眼角桃花
眼角桃花 2021-01-23 07:45

I have some problem which has stumped my beginner-knowledge of python and I hope someone out there can point me in the correct direction.

I generated a nested list, each

5条回答
  •  有刺的猬
    2021-01-23 08:02

    Here's a variation on m170897017's technique:

    a = [[1, 0],[1, 2],[2, 9],[3, 0],[3, 8],[3, 1]]
    
    result = {}
    for day, val in a:
        if day not in result:
           result[day] = 0
        result[day] += val
    
    print result
    
    #Convert back into a list
    print [list(t) for t in result.items()]
    

    output

    {1: 2, 2: 9, 3: 9}
    [[1, 2], [2, 9], [3, 9]]
    

    If you're using Python 2.7 or later, you could also use a Counter.

    Another possibility is to use a defaultdict, which has been available since Python 2.5.

    from collections import defaultdict
    
    a = [[1, 0],[1, 2],[2, 9],[3, 0],[3, 8],[3, 1]]
    
    result = defaultdict(int)
    for day, val in a:
        result[day] += val
    
    print [list(t) for t in result.items()]
    

    output

    [[1, 2], [2, 9], [3, 9]]
    

提交回复
热议问题