Reputation: 2945
I have an arbitrary list of date strings (mm-yyyy) as follows:
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?
Upvotes: 48
Views: 60741
Reputation: 3735
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'))
Upvotes: 83
Reputation: 59974
Use sorted()
with a key:
>>> 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 :))
Note that this will return the sorted list. If you want to sort it in place, use .sort()
:
>>> d.sort(key=sorting)
>>> d
['05-2006', '12-2006', '04-2007', '08-2007', '09-2012', '11-2012', '05-2013']
Upvotes: 11