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
lambdas 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
defto 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))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)