
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Matrix by Maximum Row Element in Python
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.
Advertisements