【发布时间】:2010-07-07 12:34:59
【问题描述】:
我有一个有序(即排序的)列表,其中包含按升序排序(作为日期时间对象)的日期。
我想编写一个函数来遍历这个列表并生成另一个每个月第一个可用日期的列表。
例如,假设我的排序列表包含以下数据:
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 = [],[] # <- is this even legal?
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”吗?
【问题讨论】:
-
@"# 多重赋值
-
for (curr_date in input_list)是语法错误; Python 中没有括号。 -
您的示例数据由字符串组成,在您写的文本中,您有日期时间对象。您也许应该澄清一下,一些解决方案是特定于字符串的,您必须为 datetime 对象稍微重写它们。
-
@Fabian:在撰写问题时,我意识到了“冲突”——但我不太确定如何在文本中表示日期时间对象。 Python 程序员有没有使用约定?
标签: python