w3resource

Python: Sort a given matrix in ascending order according to the sum of its rows using lambda


30. Matrix Row Sum Sort Lambda

Write a Python program to sort a given matrix in ascending order according to the sum of its rows using lambda.

Sample Solution:

Python Code :

# Define a function 'sort_matrix' that takes a matrix 'M' (list of lists) as input
def sort_matrix(M):
    # Sort the matrix 'M' based on the sum of elements in each row using the 'sorted' function
    # The 'key' parameter uses a lambda function to calculate the sum of each matrix row
    result = sorted(M, key=lambda matrix_row: sum(matrix_row)) 
    
    # Return the sorted matrix
    return result

# Define two matrices 'matrix1' and 'matrix2' as lists of lists
matrix1 = [[1, 2, 3], [2, 4, 5], [1, 1, 1]]
matrix2 = [[1, 2, 3], [-2, 4, -5], [1, -1, 1]]

# Print the original matrix 'matrix1'
print("Original Matrix:")
print(matrix1)

# Sort matrix1 based on the sum of its rows and print the sorted result
print("\nSort the said matrix in ascending order according to the sum of its rows") 
print(sort_matrix(matrix1))

# Print the original matrix 'matrix2'
print("\nOriginal Matrix:")
print(matrix2) 

# Sort matrix2 based on the sum of its rows and print the sorted result
print("\nSort the said matrix in ascending order according to the sum of its rows") 
print(sort_matrix(matrix2)) 

Sample Output:

Original Matrix:
[[1, 2, 3], [2, 4, 5], [1, 1, 1]]

Sort the said matrix in ascending order according to the sum of its rows
[[1, 1, 1], [1, 2, 3], [2, 4, 5]]

Original Matrix:
[[1, 2, 3], [-2, 4, -5], [1, -1, 1]]

Sort the said matrix in ascending order according to the sum of its rows
[[-2, 4, -5], [1, -1, 1], [1, 2, 3]]

For more Practice: Solve these Related Problems:

  • Write a Python program to sort a matrix in descending order according to the product of its rows using lambda.
  • Write a Python program to sort a matrix based on the maximum element in each row using lambda.
  • Write a Python program to sort a matrix based on the difference between the first and last elements of each row using lambda.
  • Write a Python program to sort a matrix by the average of its rows in descending order using lambda.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find the maximum value in a given heterogeneous list using lambda.
Next: Write a Python program to extract specified size of strings from a give list of string values using lambda.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.