Sum nested lists based on condition in Python

后端 未结 6 1608
感情败类
感情败类 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:30

    nl = [['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]]
    d = {}
    for l in nl:
        key = l[0] , l[1]
        value = l[2:]
        if key not in d:
            d[key] = value
        else:
            d[key] = [sum(i)for i in zip(d[key], value)]
    print(d)
    

    out:

    {('Vienna', '2012'): [890, 503, 70], ('London', '2014'): [10200, 949, 168], ('Bern', '2013'): [800, 1150, 768], ('Vienna', '2013'): [700, 850, 90]}
    

提交回复
热议问题