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