jse*_*g32 2 python list-comprehension date
所以我有这个清单:
snapshots = ['2014-04-05',
'2014-04-06',
'2014-04-07',
'2014-04-08',
'2014-04-09']
Run Code Online (Sandbox Code Playgroud)
我想找到一个使用列表理解的最早日期.
这是我现在拥有的,
earliest_date = snapshots[0]
earliest_date = [earliest_date for snapshot in snapshots if earliest_date > snapshot]
Run Code Online (Sandbox Code Playgroud)
当我打印最早的日期时,我期望返回一个空数组,因为列表的第一个元素之后的所有值都已经大于第一个元素,但我想要一个值.
这是原始代码,表示我知道如何找到最小日期值:
for snapshot in snapshots:
if earliest_date > snapshot:
earliest_date = snapshot
Run Code Online (Sandbox Code Playgroud)
有人有什么想法吗?
Mar*_*ers 14
只需使用min()或max()查找最早或最晚的日期:
earliest_date = min(snapshots)
lastest_date = max(snapshots)
Run Code Online (Sandbox Code Playgroud)
当然,如果您的日期列表已经排序,请使用:
earliest_date = snapshots[0]
lastest_date = snapshots[-1]
Run Code Online (Sandbox Code Playgroud)
演示:
>>> snapshots = ['2014-04-05',
... '2014-04-06',
... '2014-04-07',
... '2014-04-08',
... '2014-04-09']
>>> min(snapshots)
'2014-04-05'
Run Code Online (Sandbox Code Playgroud)
一般来说,列表推导应仅用于构建列表,而不是用作通用循环工具.这就是for循环的用途,真的.