57

I have an array like this:

[['G', 10], ['A', 22], ['S', 1], ['P', 14], ['V', 13], ['T', 7], ['C', 0], ['I', 219]]

I'd like to sort it based on the 2nd element in descending order. An ideal output would be:

[['I', 219], ['A', 22], ['P', 14], ... ]
Federico Capello
  • 1,088
  • 3
  • 12
  • 21

4 Answers4

95

list.sort, sorted accept optional key parameter. key function is used to generate comparison key.

>>> sorted(lst, key=lambda x: x[1], reverse=True)
[['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]

>>> sorted(lst, key=lambda x: -x[1])
[['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]

>>> import operator
>>> sorted(lst, key=operator.itemgetter(1), reverse=True)
[['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Too late but Can you explain to me what the **lambda** function does? – Ishaan Mar 28 '19 at 13:32
  • 1
    The return value of the lambda will be used as sort key. About `lambda` itself, please read the python documentation: https://docs.python.org/3/tutorial/controlflow.html?highlight=lambda#lambda-expressions – falsetru Mar 29 '19 at 00:26
  • is operator.itemgetter(1) faster than lambda? – Antonio SEO Dec 16 '19 at 03:21
12

Use itemgetter

from operator import itemgetter
a = [[1, 3, 5], [2, 511, 7], [17, 233, 1]]
a = sorted(a, key=itemgetter(1))

Output : [[1, 3, 5], [17, 233, 1], [2, 511, 7]]

itemgetter can also be used to sort by multiple subarrays.

Ugnius Malūkas
  • 2,649
  • 7
  • 29
  • 42
4

Do this:

Sort the multi-dimensional array in descending order on the basis of 2nd column:

list_name.sort(key=lambda x:x[1],reverse=True)
EliteRaceElephant
  • 7,744
  • 4
  • 47
  • 62
1
x= [[8, 9, 7],
    [1, 2, 3],
    [5, 4, 3],
    [4, 5, 6]]
x.sort(cmp=lambda x,y: cmp(x[0],y[0]))
print x
Manik
  • 21
  • 3