Python - Summing elements on list of lists based on first element of inner lists

前端 未结 4 841
谎友^
谎友^ 2021-01-20 10:55

I have a list

[[0.5, 2], [0.5, 5], [2, 3], [2, 6], [2, 0.6], [7, 1]]

I require the output from summing the second element in each sublist f

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-20 11:23

    Will this work?

    L = [[0.5, 2], [0.5, 5], [2, 3], [2, 6], [2, 0.6], [7, 1]]
    nums = []
    d = {}
    for lst in L:
        if lst[0] not in d:
            d[lst[0]] = []
            nums.append(lst[0])
        d[lst[0]].append(lst[1])
    
    for key in nums:
        print [key, sum(d[key])]
    

    Output:

    [0.5, 7]
    [2, 9.6]
    [7, 1]
    

提交回复
热议问题