Reputation: 489
In the following list of lists, I am looking to extract a list of lists grouped by the first element of each subblist. Within each group, I would like to add up the respective values of the remaining elements.
ex = [['1', -104.08, -1],
['1', 629.58, 5],
['1', 1032.51, 4],
['1', -308.18, -9],
['3', -987.18, 34],
['3',-1153.71, -21],
['3', -88.08, 75],
['3', -139.34, -85],
['6', 141.7, 90],
['6', 14.77, 4],
['6', 74.6, -5]]
The result should be something like this:
list_result = [['1', 1249.83, -1],
['3', -2368.31, 3],
['6', 231.07, 89]]
I have tried by methods like list (set ())
, to set the key, and then I have summed manually, but I am sure that there are more efficient ways with fewer lines.
Upvotes: 1
Views: 109
Reputation: 114518
itertools.groupby
should be suitable if your list is already sorted by the first element:
from itertools import groupby
from operator import itemgetter
result = []
for k, g in groupby(ex, itemgetter(0)):
_, a, b = zip(*g)
result.append([k, sum(a), sum(b)])
You can write a somewhat illegible and wasteful one-liner:
[[k, sum(a), sum(b)] for k, (_, a, b) in ((k, zip(*g)) for k, g in groupby(ex, itemgetter(0)))]
Upvotes: 3
Reputation: 61
as this q for me, i will make a dict to get same value and change it to a list
ex = [['1', -104.08, -1],
['1', 629.58, 5],
['1', 1032.51, 4],
['1', -308.18, -9],
['3', -987.18, 34],
['3',-1153.71, -21],
['3', -88.08, 75],
['3', -139.34, -85],
['6', 141.7, 90],
['6', 14.77, 4],
['6', 74.6, -5]]
e = dict()
for i in ex:
if i[0] in e.keys():
e[i[0]][0] = e[i[0]][0]+i[1]
e[i[0]][1] = e[i[0]][1]+i[2]
else:
e[i[0]] = [i[1], i[2]]
e1 = [[k,v[0],v[1]] for k,v in e.items()]
print(e1)
# output:
# [['1', 1249.83, -1], ['3', -2368.31, 3], ['6', 231.07, 89]]
Upvotes: 1