Python 对日期字符串列表进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17627531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:43:11  来源:igfitidea点击:

Sort list of date strings

pythondatetime

提问by user2480542

I have an arbitrary list of date strings (mm-yyyy) as follows:

我有一个任意的日期字符串列表 (mm-yyyy),如下所示:

d = ['09-2012', '04-2007', '11-2012', '05-2013', '12-2006', '05-2006', '08-2007'...]

I need this list to be sorted first by the level of years (ascending), then on the level of months (ascending)..so that the logical ordering can be:

我需要先按年级别(升序)对这个列表进行排序,然后按月级别(升序)排序。这样逻辑顺序可以是:

d_ordered = ['05-2006', '12-2006', '04-2007', '08-2007', '09-2012', '11-2012', '05-2013' ...]

How can I achieve this?

我怎样才能做到这一点?

采纳答案by amatellanes

Try this:

尝试这个:

import datetime
d = ['09-2012', '04-2007', '11-2012', '05-2013', '12-2006', '05-2006', '08-2007']
sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))

回答by TerryA

Use sorted()with a key:

使用sorted()一键:

>>> d = ['09-2012', '04-2007', '11-2012', '05-2013', '12-2006', '05-2006', '08-2007']
>>> def sorting(L):
...     splitup = L.split('-')
...     return splitup[1], splitup[0]
... 
>>> sorted(d, key=sorting)
['05-2006', '12-2006', '04-2007', '08-2007', '09-2012', '11-2012', '05-2013']

It's better to use a function here instead of a lambda to prevent calling split()twice (and it looks a bit neater :))

最好在这里使用函数而不是 lambda 来防止调用split()两次(而且看起来更整洁 :))

Note that this will return the sorted list. If you want to sort it in place, use .sort():

请注意,这将返回排序列表。如果要就地排序,请使用.sort()

>>> d.sort(key=sorting)
>>> d
['05-2006', '12-2006', '04-2007', '08-2007', '09-2012', '11-2012', '05-2013']