solinvictus
solinvictus

Reputation: 177

Sorting a list using two keys

I have a list of strings which i want to sort according to number of dots(.) in the given string and if the number of dots in those strings is equal i want them to be sorted by their length.(Both in descending order should not be a problem anyway)

The first part could be implemented easily

given_list.sort(key=dots,reverse=True)

dots function is implemented and it works fine.

This is where i am stuck as I am unable to sort the already sorted list according to their lengths if the number of dots is equal.

Which leads me to think i should somehow customize the key parameter using lambda, but it does not really work as it should , but it does in the case of nested lists or dictionaries .

how do i get this done?

Upvotes: 0

Views: 332

Answers (1)

Anshul Goyal
Anshul Goyal

Reputation: 76877

You can pass in a custom lambda function to the sorted method as the sorting key.

In this case, I use a lambda x: (x.count("."), len(x)), which will create a composite key of count and length, and sort accordingly:

>>> given_list = ["e.x.a", "m.p.l.e", "ex.am.ple"]
>>> sorted(given_list, key=lambda x: (x.count("."), len(x)))
['e.x.a', 'ex.am.ple', 'm.p.l.e']
>>> sorted(given_list, key=lambda x: (x.count("."), len(x)), reverse=True)
['m.p.l.e', 'ex.am.ple', 'e.x.a']

Since you are using .sort, you can do the same here as well to sort the list in-place:

>>> given_list = ["e.x.a", "m.p.l.e", "ex.am.ple"]
>>> given_list.sort(key=lambda x: (x.count("."), len(x)), reverse=True)
>>> given_list
['m.p.l.e', 'ex.am.ple', 'e.x.a']

Upvotes: 5

Related Questions