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
You can achieve the result you want by simply using a dictionary store all the country names and years as one value. Each key in the dictionary is a tuple of the country name and the corresponding year.
Ex: key = (country,year)
.
This allows us to have the unique values that we need to group them by.
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]
]
countries = {}
for list in L:
key = tuple(list[0:2])
values = list[2:]
if key in countries:
countries[key] = [sum(v) for v in zip(countries[key],values)]
else:
countries[key] = values
print(countries)
out:
{
('Vienna', '2012'): [890, 503, 70],
('London', '2014'): [10200, 949, 168],
('Bern', '2013'): [800, 1150, 768],
('Vienna', '2013'): [700, 850, 90]
}