I have a list with sublists as follows:
result = [ ['helo', 10], ['bye', 50], ['yeah', 5], ['candy',30] ]
I want to sort this with three conditions: first, by highrest integer in index 2 of sublist, then by length of word in index 1 of sublist, and finally by alphabetical order in the 1st index of sublist.
I tried to do the following but it does not work:
finalresult = sorted(result, key=lambda word: (-word[1], len(word), word[0]))
This sorts it by the highest integer and alphabet order but not by length of word.
Any help is appreciated. Thank You.
If we call the . sort method with key=condition , our list gets sorted by this score that is generated by the condition function. To be more specific, elements in our list gets sorted by the first number in the list (length), then the second number in the list (number of a ).
To sort a list of tuples by multiple elements in Python: Pass the list to the sorted() function. Use the key argument to select the elements at the specific indices in each tuple. The sorted() function will sort the list of tuples by the specified elements.
sort(key=len) , the key argument must be a function that takes in 1 argument. Whatever this function returns will be the condition that Python will sort our list by.
every element is a list of 2 elements, sorting by the length of the list is useless because all of them has the same length, maybe you want to sort by the length of the first element so
finalresult = sorted(result, key=lambda word: (-word[1], len(word[0]), word[0]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With