我有列表列表
list1 = [['0', '2015-12-27', '64236.62'],
['1', '2015-12-12', '65236.12'],
... ]
此列表包含 2015 年至 2018 年的数据 如何计算每个月的值(value)? 因此,我想创建一个字典,其中包含某一年每个月的数据。
我尝试过这样的:
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])
最佳答案
使用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}
关于python - 如何从包含日期和列表中其他字符串的字符串列表中解析月份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52704172/