I have a nested list looking like this:
[[\'Vienna\',\'2012\', 890,503,70],[\'London\',\'2014\', 5400, 879,78],
[\'London\',\'2014\',4800,70,90],[\'Bern\',\'201
The solution using itertools.groupby
and operator.itemgetter
functions:
import itertools, operator
l = [['Vienna','2012', 890,503,70],['London','2014', 5400, 879,78],
['London','2014',4800,70,90],['Bern','2013',300,450,678],
['Vienna','2013', 700,850,90], ['Bern','2013',500,700,90]]
getter = operator.itemgetter(0, 1) # the sequence to be grouped(first two items)
summed = [[k[0],k[1],sum(sum(d[2:]) for d in list(group))]
for k, group in itertools.groupby(sorted(l, key=getter), getter)]
print(summed)
The output:
[['Bern', '2013', 2718], ['London', '2014', 11317], ['Vienna', '2012', 1463], ['Vienna', '2013', 1640]]