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

Time:10-27

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

  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

CodePudding user response:

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].

  • Related