Sum nested lists based on condition in Python

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

    One way is to split the list of lists into a dict by the key you want (the city and year). Also the defaultdict helps squashing all distances into a flat list

    >>> from collections import defaultdict
    >>> dct = defaultdict(list)
    >>> for item in lst:
    ...    dct[(item[0], item[1])].extend(item[2:])
    

    Now dct has the integers grouped by the city and year:

    >>> dct
    defaultdict(, {('Vienna', '2013'): [700, 850, 90], ('London', '2014'): [5400, 879, 78, 4800, 70, 90], ('Vienna', '2012'): [890, 503, 70], ('Bern', '2013'): [300, 450, 678, 500, 700, 90]})
    

    And you can just sum them:

    >>> for key in dct:
    ...    print(key, sum(dct[key]))
    ... 
    (('Vienna', '2013'), 1640)
    (('London', '2014'), 11317)
    (('Vienna', '2012'), 1463)
    (('Bern', '2013'), 2718)
    

提交回复
热议问题