Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort list of strings using lambda and with multiple conditions in python

I have a list of strings and I want to sort the resulting list by string length. Strings with equal length should be sorted by how often the letter ’A’ occurs in them, so that the ones with the largest number of As come first and the others next. I have tried using lambda function to sort but its not working

result = sorted(result, key=len)
or
result.sort(lambda x,y: cmp(len(x), len(y)))

This is perfectly sorting based on the length of the string, but I have another condition to sort on number of As if the length is equal, how can I achieve this?

I have tried the following and yet was not able to figure it out

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  result.sort(key = (lambda x,y: 1 if len(x)>len(y) else (-1 if len(x)<len(y) else (1 if x.count("A")>y.count("A") else -1))))


 result = sorted(result, lambda x,y: 1 if len(x)>len(y) else (-1 if len(x)<len(y) else (1 if x.count("A")>y.count("A") else -1)))

I have tried both sort and sorted and I always get an error
sort() takes no positional arguments
if I don’t specify key= Infront of lambda and sorted expected 1 arguments, got 2

>Solution :

You can try

a = ["AAd", "aAAd", "AAAd", "adAA"]
a.sort(key=lambda x: (len(x), -x.count('A')))
# output
[ 'AAd', 'AAAd', 'aAAd', 'adAA']

We are firstly sorting based on the length if length is equal then sort based on -x.count('A') so if we have 3 elements then we do counting of A in them, lets say counting is [3, 2, 1] so if we arrange them in ascending order we will get [1,2,3] but we need [3,2,1] so we appended negative sign in them like this [-3, -2, -1].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading