Sum nested lists based on condition in Python

后端 未结 6 1606
感情败类
感情败类 2021-01-29 01:46

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         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-29 02:34

    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]
    }
    

提交回复
热议问题