我有一个字典列表,如下所示。每本字典都包含特定月份的总数。如果一个月没有出现在列表中,例如1月份,则总数应为零。Python:用零填充缺失的月份
q = [{'total_item': 3, 'month': u'02'}, {'total_item': 1, 'month': u'03'}, {'total_item': 1, 'month': u'05'}, {'total_item': 5, 'month': u'06'}, {'total_item': 6, 'month': u'07'}, {'total_item': 1, 'month': u'10'}, {'total_item': 1, 'month': u'12'}]
我想上面的数据结构转换成一个简单的列表,其中顺序位置代表月份和值表示的全部项目。
[0, 3, 1, 0, ...] # 12 entries in total - one for each month
也就是说一月是0,二月是3月1等
我知道我可以使用这样的事情来获得当前值:
result = [r['total_item'] for r in q]
但怎么办我为不存在的月份创建零值条目?
这会在12月产生一个IndexError :) – 2011-05-08 19:01:54
不应该,如果January是'0' ...但显然输入数据是使用1作为'1',这很容易修复。 – Amber 2011-05-08 19:06:02