Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort in python with multiple conditions?

Tags:

python

sorting

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.

like image 203
Hell Man Avatar asked Oct 04 '13 13:10

Hell Man


People also ask

How do you sort a list with two conditions in Python?

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

How do you sort a list with multiple values in Python?

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.

How do you sort by condition in Python?

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.


1 Answers

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]))
like image 95
lelloman Avatar answered Sep 30 '22 01:09

lelloman