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

通过在列表中的两个日期之间迭代来构建月份列表(Python),python,Python,我有一个有序列表,即排序列表,其中包含按升序排序为datetime对象的日期 我想写一个函数,遍历这个列表并为每个月生成另一个第一个可用日期列表 例如,假设我的排序列表包含以下数据: 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'

我有一个有序列表,即排序列表,其中包含按升序排序为datetime对象的日期

我想写一个函数,遍历这个列表并为每个月生成另一个第一个可用日期列表

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

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”功能?

搜索列表是一项打开操作。我想你可以简单地检查一下钥匙是否是新的:

>>> import itertools
>>> [min(j) for i, j in itertools.groupby(A, key=lambda x: x[:7])]
['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):
    output = []
    last_key = None
    for curr_date in input_list:
        date_key = curr_date.date.month, curr_date.date.year  # no string key required
        if date_key != last_key:
            output.append(curr_date)
            last_key = date_key
    return output

这里有一个经典python的简单解决方案,即没有itertools;不言自明

visited = {}
B = []
for a in A:
    month = a[:7]
    if month not in visited:
        B.append(a)
    visited[month] = 1

print 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']

@输入列表中的当前日期为语法错误;Python中没有括号。示例数据由字符串组成,在您编写的文本中有datetime对象。您也许应该澄清一下,有些解决方案是针对字符串的,您必须稍微重写datetime对象的解决方案。@Fabian:我在撰写问题时意识到了这种“冲突”——但我不太确定如何在文本中表示datetime对象。有Python程序员使用的约定吗?很好但是,我不明白。想解释一下发生了什么,让我们这些凡人都能理解吗?查看itertools.groupby文档。如果使用此解决方案,请确保列表已排序,否则它将不起作用。@Morphase:I根据日期字符串的前7个字符对日期进行分组,然后从组中选择最小值,该值构成输出列表的一个元素。@Fabian:list A需要按月份排序,例如,['2001/01/03'、'2001/01/01'、'2001/01/05']仍将产生['2001/01/01']我对我的语句简化得太多了,列表只需要用相同的键函数排序或以等效的方式生成。@phillip:+1获取有用的提示!。顺便说一句,您正在将变量赋值给一-发生了什么事?。在Python中,整数的逗号运算符是否重载?@morphase:comma是Python中的标准运算符。va表达式x,y的lue是由x和y组成的元组。在原始示例中,[],[]也只是由两个空列表组成的元组。