在Python中使用列表推导查找最小/最大日期 [英] Finding Min/Max Date with List Comprehension in Python
问题描述
所以我有这个列表:
snapshots = ['2014-04-05',
'2014-04-06',
'2014-04-07',
'2014-04-08',
'2014-04-09']
我想使用列表理解来查找最早的日期.
I would like to find the earliest date using a list comprehension.
这里是我现在拥有的,
earliest_date = snapshots[0]
earliest_date = [earliest_date for snapshot in snapshots if earliest_date > snapshot]
当我打印最早的日期时,我期望返回一个空数组,因为列表的第一个元素之后的所有值已经大于第一个元素,但是我想使用一个值.
When I print the earliest date, I expect an empty array back since all the values after the first element of the list are already greater than the first element, but I WANT a single value.
这是原始代码,只是表示我知道如何查找最小日期值:
Here's the original code just to signify i know how to find the min date value:
for snapshot in snapshots:
if earliest_date > snapshot:
earliest_date = snapshot
有人有什么想法吗?
推荐答案
只需使用 min()
或 max()
查找最早或最新日期:>
Just use min()
or max()
to find the earliest or latest dates:
earliest_date = min(snapshots)
lastest_date = max(snapshots)
当然,如果您的日期列表已经排序,请使用:
Of course, if your list of dates is already sorted, use:
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
循环的用途.
Generally speaking, a list comprehension should only be used to build lists, not as a general loop tool. That's what for
loops are for, really.
这篇关于在Python中使用列表推导查找最小/最大日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!