Order a matrix by columns with priority

Peter Otten __peter__ at web.de
Wed May 31 11:26:42 EDT 2017


1024masi at gmail.com wrote:

> i have the following matrix:
> catch = [['fc', 2, 12, 2],
>  ['abcd', 1, 2, 0],
>  ['ab', 1, 0, 0],
>  ['cf', 1, 13, 0],
>  ['fc', 1, 14, 0],
>  ['f', 1, 11, 0]]
> 
> and i want this matrix to be ordered by the third columns firstly, when
> the values of the third column are equals, by the second column.
> 
> i just used
> catch.sort(key=lambda x: x[3])
> to sort the matrix by third column

You can use

catch.sort(key=lambda x: (x[3], x[2]))

or, because sort() is "stable" do it in two steps

catch.sort(key=lambda x: x[2]) # least significant sort first
catch.sort(key=lambda x: x[3])

Instead of the lambda you can use operator.itemgetter():

>>> from pprint import pprint
>>> from operator import itemgetter
>>> catch = [['fc', 2, 12, 2],
...  ['abcd', 1, 2, 0], 
...  ['ab', 1, 0, 0], 
...  ['cf', 1, 13, 0], 
...  ['fc', 1, 14, 0],
...  ['f', 1, 11, 0]]
>>> catch.sort(key=itemgetter(3, 2))
>>> pprint(catch)
[['ab', 1, 0, 0],
 ['abcd', 1, 2, 0],
 ['f', 1, 11, 0],
 ['cf', 1, 13, 0],
 ['fc', 1, 14, 0],
 ['fc', 2, 12, 2]]





More information about the Python-list mailing list