Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of lists ascending and then descending

Tags:

python

sorting

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.

like image 962
Ominus Avatar asked Jul 12 '11 15:07

Ominus


People also ask

How do you sort a list in ascending order or descending order?

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.

How do I sort lists within a list?

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.

How do I reverse a list sort in Python?

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.


1 Answers

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]] 
like image 105
Steven Rumbalski Avatar answered Sep 24 '22 04:09

Steven Rumbalski