w3resource

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

Python Lambda: Exercise-30 with Solution

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]]

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.