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

前端 未结 4 848
谎友^
谎友^ 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:40

    Accumulate with a defaultdict:

    >>> from collections import defaultdict
    >>> data = defaultdict(int)
    >>> L = [[0.5, 2], [0.5, 5], [2, 3], [2, 6], [2, 0.6], [7, 1]]
    >>> for k, v in L:
    ...     data[k] += v
    ...     
    >>> [[k,v] for (k,v) in data.items()]
    [[0.5, 7], [2, 9.6], [7, 1]]
    

    Note that the value for 2 was automatically "promoted" to a float by addition, even though this is a defaultdict of int. This is to match the desired output posted in the question, but I think you should consider to use homogeneous output types rather than a mix of int and float.

提交回复
热议问题