用Python中的列表理解查找最小/最大日期

2024-06-10 10:15:26 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有这个清单:

snapshots = ['2014-04-05',
        '2014-04-06',
        '2014-04-07',
        '2014-04-08',
        '2014-04-09']

我想用列表理解法找出最早的日期。

这就是我现在所拥有的

earliest_date = snapshots[0]
earliest_date = [earliest_date for snapshot in snapshots if earliest_date > snapshot]

当我打印最早的日期时,我希望返回一个空数组,因为列表第一个元素之后的所有值都已经大于第一个元素,但是我需要一个值。

这是最初的代码,表示我知道如何找到最小日期值:

for snapshot in snapshots:
    if earliest_date > snapshot:
        earliest_date = snapshot

有人有什么想法吗?


Tags: 代码in元素列表fordateifsnapshot
2条回答

只需使用min()max()即可找到最早或最晚的日期:

earliest_date = min(snapshots)
lastest_date = max(snapshots)

当然,如果您的日期列表已经排序,请使用:

earliest_date = snapshots[0]
lastest_date = snapshots[-1]

演示:

>>> snapshots = ['2014-04-05',
...         '2014-04-06',
...         '2014-04-07',
...         '2014-04-08',
...         '2014-04-09']
>>> min(snapshots)
'2014-04-05'

一般来说,列表理解应该只用于构建列表,而不是作为一般的循环工具。这就是for循环的真正用途。

>>> snapshots = ['2014-04-05',
        '2014-04-06',
        '2014-04-07',
        '2014-04-08',
        '2014-04-09']

>>> min(snapshots)
2014-04-05

您可以使用^{}函数。

但是,这假设您的日期格式为YYYY-MM-DD,因为您的列表中有字符串。

相关问题 更多 >