Sort list of lists ascending and then descending

Something like

def mycmp(a, b):

  res = cmp(a[0], b[0])
  if res == 0:
     return cmp(a[1], b[1])
  return res

newlist = sorted(input_list, cmp=mycmp)

The comparison method first checks the first item of each element. If they are equal it will check the second items of each element. The return value inside the mycmp() implementation may be negated in order to implemented a different sorting behavior.


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]]

You can do successive rounds of sorting as python's sort is stable. You need to first sort on the secondary key though. See also the official HOW TO.

from operator import itemgetter
l = [['a',2], ['a',1], ['b', 2], ['a',3], ['b',1], ['b',3]]
l.sort(key=itemgetter(1))
l.sort(key=itemgetter(0), reverse=True)
# [['b', 1], ['b', 2], ['b', 3], ['a', 1], ['a', 2], ['a', 3]]

Tags:

Python

Sorting