在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
有没有人有什么想法?
3 个回答
0
如果你在排序列表的时候遇到问题,可以把列表里的元素转换成日期,然后找出最大值或最小值。
from dateutil import parser
snapshots = ['2014-04-05',
'2014-04-06',
'2014-04-07',
'2014-04-08',
'2014-04-09']
snapshots = [parser.parse(i).date() for i in snapshots ]
max_date = max(snapshots )
min_date = min(snapshots )
print(max_date)
print(min_date)
1
>>> snapshots = ['2014-04-05',
'2014-04-06',
'2014-04-07',
'2014-04-08',
'2014-04-09']
>>> min(snapshots)
2014-04-05
你可以使用 min
这个函数。
不过,这个方法假设你的日期格式是 YYYY-MM-DD,因为你列表里的内容是字符串。
22
只需要用 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
循环就是为了这个目的。