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

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

    Using Pandas, you can retain the original 'order' of the data:

    pairs = [[0.5, 2], [0.5, 5], [2, 3], [2, 6], [2, 0.6], [7, 1]]
    df = pd.DataFrame(pairs)
    >>> [tup[0] for tup in zip(df.groupby(0, sort=False, as_index=False).sum().values.tolist())]
    [[0.5, 7.0], [2.0, 9.6], [7.0, 1.0]]
    

提交回复
热议问题