我有名单
list1 = [['0', '2015-12-27', '64236.62'],
['1', '2015-12-12', '65236.12'],
... ]这份清单包含2015年至2018年的数据,如何计算每个月的价值?因此,我想创建一个字典,每个月的数据,在一定的一年。
我试过这样做:
import re
years_month_count = {}
for i in list1:
match = re.search("[2][0][1][5-8]-[0-9][0-9]", i[1])
if match not in years_month_count:
years_month_count[match] = 0
else:
years_month_count[match] += float(i[2])发布于 2018-10-08 14:19:13
使用str.rsplit和collections.defaultdict,您可以执行以下操作:
from collections import defaultdict
list1 = [['0', '2015-12-27', '64236.62'],
['1', '2015-11-12', '65236.12'],
['2', '2015-12-27', '64236.62']]
d = defaultdict(float)
for x in list1:
d[x[1].rsplit('-', 1)[0]] += float(x[2])输出将是类似于dict的:
{'2015-12': 128473.24, '2015-11': 65236.12}发布于 2018-10-08 14:30:02
您不应该使用else子句,因为您总是希望添加值,即使是在一个月的第一项。
另外,您不需要正则表达式。如果所有的数据存储都是格式良好的,您可以简单地使用字符串切片。
years_month_count = {}
for _, date, value in list1:
month = date[:7]
years_month_count[month] = float(value) + years_month_count.get(month, 0)发布于 2018-10-08 14:57:27
https://stackoverflow.com/questions/52704172
复制相似问题