When it is required to sort matrix by maximum row element, a method is defined that takes one parameter and uses ‘max’ method to determine the result.
Example
Below is a demonstration of the same −
def sort_max(row): return max(row) my_list = [[15, 27, 18], [39, 20, 13], [13, 15, 56], [43, 13, 25]] print("The list is :") print(my_list) my_list.sort(key = sort_max, reverse = True) print("The result is :") print(my_list)
Output
The list is : [[15, 27, 18], [39, 20, 13], [13, 15, 56], [43, 13, 25]] The result is : [[13, 15, 56], [43, 13, 25], [39, 20, 13], [15, 27, 18]]
Explanation
A method named ‘sort_max’ is defined that takes row as a parameter, and returns maximum element of row as output.
Outside the method, a 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.
In addition to this, the ‘reverse’ parameter in ‘sort’ method is set to ‘True’ so that the list is reverse sorted.
This is the output that is displayed on the console.