- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
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 −
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)
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]]
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 Articles
- Elements greater than the previous and next element in an Array in C++
- Number of elements greater than modified mean in matrix in C++
- Python - Sort Matrix by Maximum Row element
- Find Array Elements Which are Greater Than Its Immediate Left Element?
- Rearrange an array such that every odd indexed element is greater than its previous in C++
- Previous greater element in C++
- Python Program to sort rows of a matrix by custom element count
- Program to find out the number of consecutive elements in a matrix whose gcd is greater than 1 in Python
- Python Program to Sort Matrix Rows by summation of consecutive difference of elements
- Python program to sort a tuple by its float element
- Find Array Elements Which are Greater than its Left Elements in Java?
- Python program to print Rows where all its Elementsâ€™ frequency is greater than K
- Find smallest element greater than K in Python
- Python â€“ Sort Matrix by total characters