繁体   English   中英

如何根据日期对日期进行分组?

[英]How to group dates based on day?

为了简化我的问题,我有这样的日期:

2019-10-05 # Day 1 => starting point
2019-10-07 # Day 3
2019-10-07 # Day 3
2019-10-09 # Day 5
2019-10-10 # Day 6
2019-10-10 # Day 6

结果应该是: {1: ['2019-10-05'], 3: ['2019-10-07', '2019-10-07'], and so on...}

我觉得 Python(可能是 Collections?)中有一个模块可以解决这个问题,但我不知道应该使用什么术语来解决这个问题,而不是在一天中分组日期。

在字符串和日期之间进行一些转换( strptime完成繁重的工作)......你可以这样做:

from datetime import datetime
from collections import defaultdict

# the date format (for strptime)
fmt = "%Y-%m-%d"

startdate = datetime.strptime('2019-10-05', fmt).date()

# the dates as strings
date_str_list = [
    "2019-10-07", # Day 3
    "2019-10-07", # Day 3
    "2019-10-09", # Day 5
    "2019-10-10", # Day 6
    "2019-10-10"  # Day 6
]

# converting to date objects
date_list = [datetime.strptime(date_str, fmt).date() for date_str in date_str_list]

res = defaultdict(list)
for date in date_list:
    res[(date - startdate).days + 1].append(str(date))

print(res)
# defaultdict(<class 'list'>, {3: ['2019-10-07', '2019-10-07'], 
#     5: ['2019-10-09'], 6: ['2019-10-10', '2019-10-10']})

我使用defaultdict作为容器。

两个date object 的差异是一个timedelta object; .days给出其天数。

我建议对您的输入进行 for 循环,同时记住上一个键:

# this does not support your key function returning None as the key
last_key = None
day = 1
collected = []
ret = {}

for x in values:
    key = # select the key from your data `x`
    if last_key:
        # make sure your input is ordered for the key thing to work
        assert key >= last_key
    if last_key and key != last_key:
        ret[day] = collected
        collected = []
        day += 1
    last_key = key
    collected.append(x)

if collected:
  ret[day] = collected

我不认为这是对迭代器的一般操作。 我几乎建议collections.Counter但后来意识到这是错误的答案。

也许如果您可以enumerate一个迭代器,它按顺序按键分组(而不是通过收集整个输入并对其进行排序)。 我不知道 python 中这种迭代器的名称。 根据上面的例子构建一个不会太困难:只需将ret[day] =替换为yield并删除ret

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM