Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to sort matrix based upon sum of rows
When it is required to sort a matrix based upon the sum of rows, we can use Python's built-in sort() method with a custom key function. The key function calculates the sum of each row, and the matrix is sorted in ascending order based on these sums.
Method 1: Using a Custom Function
Define a helper function that calculates the sum of a row and use it as the key for sorting ?
def sort_sum(row):
return sum(row)
matrix = [[34, 51], [32, 15, 67], [12, 41], [54, 36, 22]]
print("The matrix is :")
print(matrix)
matrix.sort(key=sort_sum)
print("The sorted matrix is :")
print(matrix)
The matrix is : [[34, 51], [32, 15, 67], [12, 41], [54, 36, 22]] The sorted matrix is : [[12, 41], [34, 51], [54, 36, 22], [32, 15, 67]]
Method 2: Using Lambda Function
A more concise approach using a lambda function ?
matrix = [[34, 51], [32, 15, 67], [12, 41], [54, 36, 22]]
print("Original matrix:")
print(matrix)
matrix.sort(key=lambda row: sum(row))
print("Sorted matrix:")
print(matrix)
Original matrix: [[34, 51], [32, 15, 67], [12, 41], [54, 36, 22]] Sorted matrix: [[12, 41], [34, 51], [54, 36, 22], [32, 15, 67]]
Method 3: Using sorted() Function
If you want to keep the original matrix unchanged, use sorted() which returns a new sorted list ?
matrix = [[34, 51], [32, 15, 67], [12, 41], [54, 36, 22]]
print("Original matrix:")
print(matrix)
sorted_matrix = sorted(matrix, key=sum)
print("Sorted matrix:")
print(sorted_matrix)
print("Original matrix remains unchanged:")
print(matrix)
Original matrix: [[34, 51], [32, 15, 67], [12, 41], [54, 36, 22]] Sorted matrix: [[12, 41], [34, 51], [54, 36, 22], [32, 15, 67]] Original matrix remains unchanged: [[34, 51], [32, 15, 67], [12, 41], [54, 36, 22]]
How It Works
The sorting is based on row sums:
[12, 41]? sum = 53 (smallest)[34, 51]? sum = 85[54, 36, 22]? sum = 112[32, 15, 67]? sum = 114 (largest)
Comparison
| Method | Modifies Original | Best For |
|---|---|---|
| Custom Function | Yes | Reusable logic |
| Lambda Function | Yes | Concise one-liners |
sorted() |
No | Preserving original data |
Conclusion
Use sort(key=sum) for in-place sorting or sorted(matrix, key=sum) to preserve the original matrix. The sum function works directly as a key since it calculates the total of each row.
