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
x.sort(C); x.sort(B); x.sort(A). No need to shoehorn everything in one single lambda.