筛选日期行的参数方式

时间:2019-01-15 03:39:17

标签: python database loops

我已经努力奋斗了一周,我尝试了双向while循环和其他dateutil的东西,但是每当计数器落后或遇到其他问题时,都没有运气

我只想找到按年和月过滤行以按月总计的最有效方法。

fls17 = [counter for counter in db_list if counter.year == 2017]
fls18 = [counter.date for counter in db_list if counter.year == 2018]
fls19 = [counter.date for counter in db_list if counter.year == 2019]

fls17_sum = sum([counter.money for counter in fls17])

这是我的数据示例,该数据已被解析,转换为datetime对象并放入数据类

[CsvDateObject(date=datetime.date(2017, 2, 1), year=2017, month=2, day=1, money=71, counter=0),
 CsvDateObject(date=datetime.date(2017, 2, 1), year=2017, month=2, day=1, money=53, counter=1),
 CsvDateObject(date=datetime.date(2017, 2, 25), year=2017, month=2, day=25, money=20, counter=2),
 CsvDateObject(date=datetime.date(2017, 12, 1), year=2017, month=12, day=1, money=35, counter=3),
 CsvDateObject(date=datetime.date(2017, 12, 25), year=2017, month=12, day=25, money=35, counter=4)]

[datetime.date(2018, 1, 1),
 datetime.date(2018, 3, 1),
 datetime.date(2018, 3, 25)]

[datetime.date(2019, 1, 1),
 datetime.date(2019, 6, 1)]

214

如果想查看我之前编写的代码的完整列表,请问我

  

++++

那是我的初始数据

csv_list = [
        ['2019-06-1', 68],
        ['2019-01-1', 68],
        ['2018-03-25', 75],
        ['2018-03-1', 75],
        ['2018-01-1', 25],
        ['2017-12-25', 35],
        ['2017-12-1', 35],
        ['2017-02-25', 20],
        ['2017-02-1', 53],
        ['2017-02-1', 71],
]
  

++++

itertools.groupby()-正是我所需要的^ _ ^

gl = list()
for k, v in groupby(db_list, key=lambda i: i.month):
    gl.append(list(v))

1 个答案:

答案 0 :(得分:1)

当然,如果我理解正确,这就是您想要的:

import datetime
from itertools import groupby
from operator import itemgetter

first = itemgetter(0)
second = itemgetter(1)

updated = [[datetime.datetime.strptime(first(l), '%Y-%m-%d').year, second(l)] for l in csv_list]

[[2019, 68],
 [2019, 68],
 [2018, 75],
 [2018, 75],
 [2018, 25],
 [2017, 35],
 [2017, 35],
 [2017, 20],
 [2017, 53],
 [2017, 71]]

d = {}
for _, g in groupby(updated, key=first):
    grouped = list(g)
    k = first(first(grouped))
    v = sum(second(group) for group in grouped)
    d[k] = v

print(d)

{2017: 214, 2018: 175, 2019: 136}