python - 如何从包含日期和列表中其他字符串的字符串列表中解析月份?

标签 python python-3.x

我有列表列表

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/

相关文章:

python - 设置 kivy 整数的最小值和最大值

python - 编写递归随机变量的更好方法

python - 如何导入辅助模块以使用需要从第一个执行模块更新全局变量的函数

python - 为什么 Keras 不需要自定义损失函数的梯度?

python - 让 python 将带引号的字符串视为一个 block

python - 属性错误 : 'Int64Index' object has no attribute 'month'

python - django 表单不显示或对象不带参数错误

python - list() 函数混淆

python - 如何组合最接近的非重叠范围?

python ipow : how to use the third argument?