Add value for each year in python list -


this question has answer here:

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

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -