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

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

    You can get away with sorting and itertools.groupby:

    from operator import itemgetter
    from itertools import groupby
    
    data = [[0.5, 2], [0.5, 5], [2, 3], [2, 6], [2, 0.6], [7, 1]]
    
    key = itemgetter(0)
    data.sort(key=key)  # Use data = sorted(data, key=key) to avoid clobbering
    result = [[k, sum(group)] for k, group in groupby(data, key)]
    

    This will not preserve the original order of the keys.

提交回复
热议问题