 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Python – Sort Matrix by Number of elements greater than its previous element
When it is required to sort a matrix based on the number of elements that is greater than the previous element, a list comprehension and the ‘len’ method is used by using a function.
Below is a demonstration of the same −
Example
def fetch_greater_freq(row):    return len([row[idx] for idx in range(0, len(row) - 1) if row[idx] < row[idx + 1]]) my_list = [[11, 3, 25, 99, 10], [5, 3, 25, 4], [77, 11, 5, 3, 77, 77], [11, 3, 25]] print("The list is :") print(my_list) my_list.sort(key=fetch_greater_freq) print("The resultant list is :") print(my_list)  Output
The list is : [[11, 3, 25, 99, 10], [5, 3, 25, 4], [77, 11, 5, 3, 77, 77], [11, 3, 25]] The resultant list is : [[5, 3, 25, 4], [77, 11, 5, 3, 77, 77], [11, 3, 25], [11, 3, 25, 99, 10]]
Explanation
- A method named ‘fetch_greater_freq’ is defined that takes a list as a parameter. 
- The list is iterated over, and a specific element is accessed and checked to see if it is less than its consecutive element. 
- Its length is returned as output of the method. 
- Outside the method, a list of list of integers is defined and is displayed on the console. 
- The list is sorted using the sort method by passing the previously defined method as the parameter. 
- The output is displayed on the console. 
Advertisements
 