Summing values in nested list when item changes

后端 未结 5 1213
眼角桃花
眼角桃花 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:03

    You can put the key in a dictionary and store the counts in the values. Like this:

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    a = [[1, 0],[1, 2],[2, 9],[3, 0],[3, 8],[3, 1]]
    res = {}
    for i in a:
        if i[0] in res:
            res[i[0]] += i[1]
        else:
            res[i[0]] = i[1]
    
    print res
    

    OUTPUT:

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

    This output is in dictionary format. You can turn it to list format as you like.

提交回复
热议问题