

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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.
- Related Questions & Answers
- Finding element greater than its adjacent elements in JavaScript
- Number of elements greater than modified mean in matrix in C++
- Elements greater than the previous and next element in an Array in C++
- Rearrange an array such that every odd indexed element is greater than its previous in C++
- Previous greater element in C++
- Python - Sort Matrix by Maximum Row element
- Python program to sort a tuple by its float element
- Python Program to sort rows of a matrix by custom element count
- Python - Number of values greater than K in list
- Find smallest element greater than K in Python
- Python Program to Sort Matrix Rows by summation of consecutive difference of elements
- Python - Get the Index of first element greater than K
- Python program to print Rows where all its Elements’ frequency is greater than K
- Program to find out the number of consecutive elements in a matrix whose gcd is greater than 1 in Python
- Python – Sort Matrix by total characters
Advertisements