填充包含日期类型数据的列表的最佳pythonic方法?

Ava*_*esh 7 python list

我有以下列表数据.

data = [['2009-01-20', 3000.0], ['2011-03-01', 6000.0], ['2008-12-15',
6000.0], ['2002-02-15', 6000.0], ['2009-04-20', 6000.0], ['2010-08-01',
4170.0], ['2002-07-15', 6000.0], ['2008-08-15', 6000.0], ['2010-12-01',
6000.0], ['2011-02-01', 8107.0], ['2011-04-01', 8400.0], ['2011-05-15',
9000.0], ['2010-05-01', 6960.0], ['2005-12-15', 6000.0], ['2010-10-01',
6263.0], ['2011-06-02', 3000.0], ['2010-11-01', 4170.0], ['2009-09-25',
6000.0]]
Run Code Online (Sandbox Code Playgroud)

其中第一个参数是date,第二个参数是total.我想从上面的列表中按月和年分组使用结果.

即结果如下:

--> for month: [['JAN',tot1],['FEB',tot2],['MAR',tot3] ...]
--> for year: [['2002',tot1],['2005',tot2],['2008',tot3] ...]
Run Code Online (Sandbox Code Playgroud)

Ste*_*joa 11

from collections import defaultdict

yeartotal = defaultdict(float)
monthtotal = defaultdict(float)
for s in data:
    d = s[0].split('-')
    yeartotal[d[0]] += s[1]
    monthtotal[d[1]] += s[1]


In [37]: [item for item in yeartotal.iteritems()]
Out[37]: 
[('2002', 12000.0),
 ('2005', 6000.0),
 ('2008', 12000.0),
 ('2009', 15000.0),
 ('2011', 34507.0),
 ('2010', 27563.0)]

In [38]: [item for item in monthtotal.iteritems()]
Out[38]: 
[('02', 14107.0),
 ('03', 6000.0),
 ('12', 18000.0),
 ('06', 3000.0),
 ('07', 6000.0),
 ('04', 14400.0),
 ('05', 15960.0),
 ('08', 10170.0),
 ('09', 6000.0),
 ('01', 3000.0),
 ('11', 4170.0),
 ('10', 6263.0)]
Run Code Online (Sandbox Code Playgroud)