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
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.