Blid Blid - 7 months ago 10
Python Question

How to sort a matrix in the ascending order by the sum of its row in Python?

The exact same question is answered here but in MATLAB.

My question is this: Given a matrix, sort it in the ascending order according to the sum of its rows.
That is, if

A
is the following matrix:

A = [[9, 8, 7],
[2, 5, 7],
[1, 3, 4]]


therefore, I would get:

B = [[1, 3, 4],
[2, 5, 7],
[9, 8, 7]]


because the sum of the 1st row of
A
is
24
, the sum of the 2nd row of
A
is
14
, and the sum of the 3rd row of
A
is
8
. Hence, the 1st row of
B
will be the 3rd row of
A
, the 2nd row of
B
will be the 2nd row of
A
, and the 3rd row of
B
will be the 1st row of
A
.

I am looking for a solution that uses built-in function (if possible). I am not looking for an algorithm for this.

Answer

There is a function available that does the trick:

sorted(A, key=sum)

gives you the desired output:

[[1, 3, 4], [2, 5, 7], [9, 8, 7]]