python日期迭代_通过在列表中的两个日期之间迭代来构建月份列表(Python)

我有一个有序(即排序)列表,其中包含按升序排序的日期(作为日期时间对象).

我想编写一个迭代这个列表的函数,并生成每个月的第一个可用日期的另一个列表.

例如,假设我的排序列表包含以下数据:

A = [

'2001/01/01',

'2001/01/03',

'2001/01/05',

'2001/02/04',

'2001/02/05',

'2001/03/01',

'2001/03/02',

'2001/04/10',

'2001/04/11',

'2001/04/15',

'2001/05/07',

'2001/05/12',

'2001/07/01',

'2001/07/10',

'2002/03/01',

'2002/04/01',

]

返回的列表将是

B = [

'2001/01/01',

'2001/02/04',

'2001/03/01',

'2001/04/10',

'2001/05/07',

'2001/07/01',

'2002/03/01',

'2002/04/01',

]

我建议的逻辑是这样的:

def extract_month_first_dates(input_list, start_date, end_date):

#note: start_date and end_date DEFINITELY exist in the passed in list

prev_dates, output = [],[] #

for (curr_date in input_list):

if ((curr_date < start_date) or (curr_date > end_date)):

continue

curr_month = curr_date.date.month

curr_year = curr_date.date.year

date_key = "{0}-{1}".format(curr_year, curr_month)

if (date_key in prev_dates):

continue

else:

output.append(curr_date)

prev_dates.append(date_key)

return output

有什么意见,建议吗? – 这可以改进为更多’Pythonic’吗?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值