Davis Merrit
Davis Merrit

Reputation: 143

Sum particular list values

I want to sum 3d list values by first two criteria. What is the best way to get from this list

a = [['Mercedes', 'AMG', 100],
['Mercedes', 'Cabrio', 200],
['Mercedes', 'AMG', 300],
['Opel', 'Combo', 400],
['Opel', 'MOKKA', 500],
['Opel', 'MOKKA', 600],
['BMW', 'X5', 700]]

this result:

result = [['Mercedes', 'AMG', 400],
['Mercedes', 'Cabrio', 200],
['Opel', 'Combo', 400],
['Opel', 'MOKKA', 1100],
['BMW', 'X5', 700]]

Upvotes: 0

Views: 83

Answers (2)

s3bw
s3bw

Reputation: 3049

Here is something you can do if you are not concerned about order:

set_list = set(map(lambda x: (x[0], x[1]), a))

result = [
    [m[0], m[1], sum([y[2] for y in a if (y[0], y[1]) == m])] 
    for m in set_list
]

Upvotes: 1

cs95
cs95

Reputation: 403020

I'll be using an OrderedDict to perform aggregation.

from collections import OrderedDict

d = OrderedDict()
for x, y, z in a:
     d[(x, y)] = d.setdefault((x, y), 0) + z

r = [list(k) + [v] for k, v in d.items()]   
r

[['Mercedes', 'AMG', 400],
 ['Mercedes', 'Cabrio', 200],
 ['Opel', 'Combo', 400],
 ['Opel', 'MOKKA', 1100],
 ['BMW', 'X5', 700]]

Upvotes: 2

Related Questions