Sum nested lists based on condition in Python

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

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

提交回复
热议问题