Reputation: 21
I have a list of lists as follows,
data = [[1, 2],[1, 10], [1, 4], [2, 3], [2, 2], [8, 3], [3,2]]
I want to group the inside lists by their first position value and then sum the second position values wherever there is a match like in the snippet below,
result = [[1,16],[2,5],[3,2],[8,3]]
how do I achieve this in pure python please?
Upvotes: 0
Views: 200
Reputation: 147146
You can use itertools.groupby
to group on the first value in each sublist, and then sum
the second value in each grouped list:
from itertools import groupby
data = [[1, 2],[1, 10], [1, 4], [2, 3], [2, 2], [8, 3], [3,2]]
groups = groupby(data, key=lambda v:v[0])
result = [[i, sum(v[1] for v in g)] for i, g in groups]
print(result)
Output:
[[1, 16], [2, 5], [8, 3], [3, 2]]
Upvotes: 1
Reputation: 4472
You can use defaultdict
for that to collect all the inner list first item and all these lists second items to a list and sum all of them.
from collections import defaultdict
data = [[1, 2],[1, 10], [1, 4], [2, 3], [2, 2], [8, 3], [3,2]]
res_dist = defaultdict(list)
for i in data:
res_dist[i[0]].append(i[1])
print(sorted([[k, sum(v)] for k, v in res_dist.items()], key=lambda x: x[0]))
Output
[[1, 16], [2, 5], [3, 2], [8, 3]]
Upvotes: 0