如果我有以下数据:
data = [[3, 2014], [4, 2014], [6, 2013], [6,2013]] etc...
在python中按年计算总和的最佳方法是什么?
最佳答案
如果您需要年份和总和,我会使用dict:
from collections import defaultdict
data = [[3, 2014], [4, 2014], [6, 2013], [6,2013]]
d = defaultdict(int)
for v, k in data:
d[k] += v
print(d)
印刷品:
defaultdict(<type 'int'>, {2013: 12, 2014: 7})