Python program to sort matrix based upon sum of rows


When it is required to sort matrix based upon sum of rows, a method is defined that uses ‘sum’ method to determine the result.

Below is a demonstration of the same −

Example

 Live Demo

def sort_sum(row):
   return sum(row)

my_list = [[34, 51], [32, 15, 67], [12, 41], [54, 36, 22]]

print("The list is :")
print(my_list)

my_list.sort(key = sort_sum)

print("The result is :")
print(my_list)

Output

The list is :
[[34, 51], [32, 15, 67], [12, 41], [54, 36, 22]]
The result is :
[[12, 41], [34, 51], [54, 36, 22], [32, 15, 67]]

Explanation

  • A method named ‘sort_sum’ is defined that takes a list as a parameter, and returns sum of the elements of the list as output.

  • A list of list is defined and displayed on the console.

  • The list is sorted using ‘sort’ method and the key is specified as the previously defined method.

  • This is the output that is displayed on the console.

Updated on: 06-Sep-2021

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements