Python - 日期上的Itemgetter

时间:2014-02-07 18:01:15

标签: python date python-3.x

from operator import itemgetter

a=[['','27/01/2014'],['','28/01/2014'],['','29/01/2014'],['','30/01/2014'],['','31/01/2014'],['','01/02/2014'],['','02/02/2014']]

b=sorted(a,key=itemgetter(-1))

输出:

[['', '01/02/2014'], ['', '02/02/2014'], ['', '27/01/2014'], ['', '28/01/2014'], ['', '29/01/2014'], ['', '30/01/2014'], ['', '31/01/2014']]

为什么itemgetter会产生这个结果?

我在示例中知道日期是按升序排列的,但假设它们不是,是否有一个函数可以简单地执行此操作?

3 个答案:

答案 0 :(得分:1)

日期存储为字符串,因此按字典顺序执行排序。如果您希望将其排序为日期,则应使用datetime.strptime

import datetime
b=sorted(a,key=lambda x:datetime.datetime.strptime(x[-1], '%d/%m/%Y'))

输出:

[['', '27/01/2014'], ['', '28/01/2014'], ['', '29/01/2014'], ['', '30/01/2014'], ['', '31/01/2014'], ['', '01/02/2014'], ['', '02/02/2014']]

答案 1 :(得分:1)

按照你的要求对它们进行排序。当然,您的日期是字符串,字符串按lexicographically排序。如果您的日期是ISO 8601格式,这仅相当于日期的自然排序顺序。你的不是。

尝试通过将每个转换为datetime函数中的key对象进行排序:

sorted(a,key=lambda x: datetime.strptime(x[1],'%d/%m/%Y'))
Out[18]: 
[['', '27/01/2014'],
 ['', '28/01/2014'],
 ['', '29/01/2014'],
 ['', '30/01/2014'],
 ['', '31/01/2014'],
 ['', '01/02/2014'],
 ['', '02/02/2014']]

答案 2 :(得分:1)

你那里没有约会。你有字符串碰巧包含日期的字符串表示。因此,当您按字符串排序时,您将使用标准lexicographical order对其进行排序。

如果您想按日期对其进行排序,您实际上需要解释这些字符串。例如,使用datetime:

>>> a = [['','27/01/2014'],['','28/01/2014'],['','29/01/2014'],['','30/01/2014'],['','31/01/2014'],['','01/02/2014'],['','02/02/2014']]
>>> a.sort(key=lambda x: datetime.strptime(x[-1], '%d/%m/%Y'))
>>> a
[['', '27/01/2014'], ['', '28/01/2014'], ['', '29/01/2014'], ['', '30/01/2014'], ['', '31/01/2014'], ['', '01/02/2014'], ['', '02/02/2014']]

如果您想使用日期,最好将它们转换为datetime对象:

>>> b = [[a, datetime.strptime(b, '%d/%m/%Y')] for a, b in a]
>>> b
[['', datetime.datetime(2014, 1, 27, 0, 0)], ['', datetime.datetime(2014, 1, 28, 0, 0)], ['', datetime.datetime(2014, 1, 29, 0, 0)], ['', datetime.datetime(2014, 1, 30, 0, 0)], ['', datetime.datetime(2014, 1, 31, 0, 0)], ['', datetime.datetime(2014, 2, 1, 0, 0)], ['', datetime.datetime(2014, 2, 2, 0, 0)]]

然后您还可以使用itemgetter

>>> from operator import itemgetter
>>> b.sort(key=itemgetter(-1))
>>> b
[['', datetime.datetime(2014, 1, 27, 0, 0)], ['', datetime.datetime(2014, 1, 28, 0, 0)], ['', datetime.datetime(2014, 1, 29, 0, 0)], ['', datetime.datetime(2014, 1, 30, 0, 0)], ['', datetime.datetime(2014, 1, 31, 0, 0)], ['', datetime.datetime(2014, 2, 1, 0, 0)], ['', datetime.datetime(2014, 2, 2, 0, 0)]]