If I have a list that contains a list that looks like this
['a',1] ['a',2] ['a',3] ['b',1] ['b',2] ['b',3]
How can I sort them so that element 0 is sorted descending and element 1 sorted ascending so the result would look like
['b',1] ['b',2] ['b',3] ['a',1] ['a',2] ['a',3]
Using itemgetter
I can pass in reverse on element 0 but I then resort against element to of course it ruins the previous sort. I can't do a combined key since it needs to first sort descending and then ascending.
Python List sort() - Sorts Ascending or Descending List. The list. sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items. Use the key parameter to pass the function name to be used for comparison instead of the default < operator.
Use the sort() Function to Sort a List of Lists in Python. The sort() method sorts the list of lists in Python according to the first element of each inner list. This method makes changes in the original list itself. We use the reverse parameter to sort in descending order.
Sort in Descending order The sort() method accepts a reverse parameter as an optional argument. Setting reverse = True sorts the list in the descending order.
L = [['a',1], ['a',2], ['a',3], ['b',1], ['b',2], ['b',3]] L.sort(key=lambda k: (k[0], -k[1]), reverse=True)
L
now contains:
[['b', 1], ['b', 2], ['b', 3], ['a', 1], ['a', 2], ['a', 3]]
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