2

I have to sort my list of strings according to the months name:

my_list = ['apple_april', 'banana_july', 'carrot_december', 'dog_january']

I have to sort by january, february, martch, .....

My trial:

months = [m.split('_')[1] for m in my_list]

ans = [x for (y,x) in sorted(zip(months,my_list))]

But no success, how would you do it?

The expected answers is:

['dog_january', 'apple_april', 'banana_july', 'carrot_december']

4 Answers 4

3

list.sort, sorted accept optional key parameter. Pass a key function that returns corresponding number to monthes.

>>> import calendar
>>>
>>> months = {calendar.month_name[i].lower(): i for i in range(1, 12+1)}
>>> my_list = ['apple_april', 'banana_july', 'carrot_december', 'dog_january']
>>> sorted(my_list, key=lambda x: months[x.split('_')[1]])
['dog_january', 'apple_april', 'banana_july', 'carrot_december']

months is mapping between month names and numbers using calendar.month_name:

>>> months
{'april': 4, 'november': 11, 'june': 6, 'august': 8, 'december': 12, 'october': 10,
 'july': 7, 'march': 3, 'september':9, 'may': 5, 'january': 1, 'february': 2}
Sign up to request clarification or add additional context in comments.

Comments

2

You could make a dictionary of months and their corresponding position in the calendar:

months = {'january': 1,
          'april': 4,
          'july': 7,
          'december': 12}

And then sort the list by looking up the month in the dictionary. First split each element of the list on the underscore (which gives a list such as ['dog', 'january']) and then use months.get to look up the last element of this list in the dictionary:

>>> sorted(my_list, key=lambda x: months.get(x.split('_')[-1]))
['dog_january', 'apple_april', 'banana_july', 'carrot_december']

Edit:

A lazier way if you have dateutil installed...

>>> import dateutil
>>> sorted(my_list, key=lambda x: dateutil.parser.parse(x.split('_')[-1]))
['dog_january', 'apple_april', 'banana_july', 'carrot_december']

No need for a dictionary! dateutil.parser.parse parses the month string to a datetime object.

4 Comments

You should be too lazy to write a dictionary of every month
I like your lazier way, it's what I wanted the answer i just submitted to be like. I gave you a vote but stackoverflow doesn't want me to tell you
Thanks - I think your answer is preferable to mine as it doesn't rely on the third-party dateutil (+1)
But if one was working with dateutil one should use this so that's good to know. I was looking up to see if strptime can accept wildcard characters but it turns out you need dateutil for that
2
>>> from datetime import datetime
>>> my_list = ['apple_april', 'banana_july', 'carrot_december', 'dog_january']
>>> sorted(my_list, key=lambda x: datetime.strptime(x.split('_')[1], '%B'))
['dog_january', 'apple_april', 'banana_july', 'carrot_december']

Comments

1

You can sort your list based on calendar.month_name or calendar.month_abbr :

>>> import calendar
>>> m=list(calendar.month_abbr)
>>> l=[(i,x) for x in my_list for i,j in enumerate(m) if j==x.split('_')[1][:3]]
>>> [i[1] for i in sorted(l,key= lambda x: x[0])]
['dog_january', 'apple_april', 'banana_july', 'carrot_december']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.