将彼此在一个时间范围内的任意日期对象分组在一起

将彼此在一个时间范围内的任意日期对象分组在一起,第1张

将彼此在一个时间范围内的任意日期对象分组在一起
import datetime as DTimport itertoolsstart_date=DT.date(2008,5,5)def mkdate(datestring):    return DT.datetime.strptime(datestring, "%Y-%m-%d").date()def fortnight(date):    return (date-start_date).days //14raw = ("2010-08-01",       "2010-06-25",       "2010-07-01",       "2010-07-08")transactions=[(date,"Some data") for date in map(mkdate,raw)]transactions.sort(key=lambda (date,data):date)for key,grp in itertools.groupby(transactions,key=lambda (date,data):fortnight(date)):    print(key,list(grp))

产量

# (55, [(datetime.date(2010, 6, 25), 'Some data')])# (56, [(datetime.date(2010, 7, 1), 'Some data'), (datetime.date(2010, 7, 8), 'Some data')])# (58, [(datetime.date(2010, 8, 1), 'Some data')])

请注意,2010-6-25是2008-5-5的第55个两周,而2010-7-1是第56个。如果您希望将它们组合在一起,只需进行更改

start_date
(更改为类似于2008-5-16的内容)。

PS。上面使用的关键工具是

itertools.groupby
,此处将对其进行详细说明。

Edit: The

lambda
s are simply a way to make “anonymous”
functions
. (They
are anonymous in the sense that they are not given names like functions
defined by
def
). Anywhere you see a lambda, it is also possible to use a
def
to create an equivalent function. For example, you could do this:

import operatortransactions.sort(key=operator.itemgetter(0))def transaction_fortnight(transaction):    date,data=transaction    return fortnight(date)for key,grp in itertools.groupby(transactions,key=transaction_fortnight):    print(key,list(grp))


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5639922.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存