thito
thito

Reputation: 5

Sort list according given text of months

How to sort the given list l according to months ['Jan', 'Feb', 'Mar'] and ['L', 'K']:

l = ['Jan_K', 'Mar_K', 'Feb_L']

The expected result should be:

result = ['Feb_L', 'Jan_K', 'Mar_K']

Upvotes: 0

Views: 2120

Answers (1)

Delgan
Delgan

Reputation: 19627

Your try is a list comprehension which actually does nothing else than creating a new list.

If you want to sort a list, you gave to use .sort().

If you want to sort a list in a particular way, you have to use .sort() with the key argument.

So, if you want the first months to come first in the list, start by creating a list containing the order of these months:

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

Then, you can use key and a lambda function like this:

l.sort(key=lambda x: months.index(x.split('_')[0]))

For example, x.split('_')[0] gives "Jan" when x is "Jan_opi", and months.index("Jan") is 0 so the element will come first.


According to your edit, if you want to sort the list based on two criterias, you just have to make the lambda function return a tuple (the sorting function compares the first value returned of two elements, and if it is the same then the second one).

letters = ['L','K']
final_result = sorted(l, key=lambda x: (letters.index(x.split('_')[1]), months.index(x.split('_')[0])))

Upvotes: 2

Related Questions