Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: how to sort a complex list on two different keys

Tags:

python

sorting

I have a weird list built in the following way:

[[name_d, 5], [name_e, 10], [name_a, 5]] 

and I want to sort it first by the number (desc) and then, if the number is the same, by the name (asc). So the result I would like to have is:

[[name_e, 10], [name_a, 5], [name_d, 5]]

I tried to think to a lambda function that I can use in the sort method, but I'm not sure I can do it.

like image 954
Giovanni Di Milia Avatar asked Oct 20 '10 16:10

Giovanni Di Milia


People also ask

Can you sort by multiple keys in Python?

Sort by multiple keysYou can specify multiple arguments for operator. itemgetter() , and if the values for the first key are equal, they will be compared and sorted by the value of the next key. Note that if the order of the arguments is different, the result is also different.

How do you sort a mixed list in Python?

Method #2 : Using sorted() + key + lambda + isdigit() In this, we just sort the list using sorted() using key functionality using lambda function to segregate digits using isdigit().

How do you sort a list with multiple elements?

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 a list with multiple criteria in Python?

sort() function. A Pythonic solution to in-place sort a list of objects using multiple attributes is to use the list. sort() function. It accepts two optional keyword-only arguments: key and reverse and produces a stable sort.


1 Answers

Sort functions in python allow to pass a function as sort key:

l = [[name_d, 5], [name_e, 10], [name_a, 5]]
# copy
l_sorted = sorted(l, key=lambda x: (x[1] * -1, x[0]))
# in place
l.sort(key=lambda x: (x[1] * -1, x[0]))

Edits:
1. Sort order
2. Demonstrate copy and in place sorting

like image 171
tback Avatar answered Nov 15 '22 16:11

tback