Add value for each year in python list -
this question has answer here:
- how sum tuples in list first value same? 4 answers
given list of [yyy,m,value], need add values corresponding single year. that,
a = [ [['2008', '3', '5'],['2008', '4', '35'],['2013', '3', '71']], [['2008', '6', '2'],['2008', '7', '2'],['2008', '8', '4'],['2013', '3', '128']] ]
becomes
a = [ [['2008', '40'],['2013','71']], [['2008', '8'],['2013','128']] ]
what best possible ways? thanks.
use defaultdict
:
from collections import defaultdict b = [] line in a: d = defaultdict(int) entry in line: d[entry[0]] += int(entry[2]) b.append([(k,str(v)) k,v in sorted(d.items(),key=lambda x: int(x[0]))])
gives
b out[71]: [[('2008', '40'), ('2013', '71')], [('2008', '8'), ('2013', '128')]]
Comments
Post a Comment