0

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?

1 Answer 1

5

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']
Sign up to request clarification or add additional context in comments.

1 Comment

Ah yeah i remember trying this but i must have messed it .Oh gosh i feel embarassed.Thanks for the help

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.