
- 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 – Sort Matrix by Row Median
When it is required to sort matrix by row median, a method is defined that uses the ‘median’ method to determine the result.
Below is a demonstration of the same −
Example
from statistics import median def median_row(row): return median(row) my_list = [[43, 14, 27], [13, 27, 24], [32, 56, 18], [34, 62, 55]] print("The list is :") print(my_list) my_list.sort(key = median_row) print("The result is :") print(my_list)
Output
The list is : [[43, 14, 27], [13, 27, 24], [32, 56, 18], [34, 62, 55]] The result is : [[13, 27, 24], [43, 14, 27], [32, 56, 18], [34, 62, 55]]
Explanation
The required packages are imported into the environment.
A method named ‘median_row’ is defined that takes row as a parameter, returns median of the row as output using ‘median’ method.
A list of 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.
This is the output that is displayed on the console.
- Related Articles
- Python - Sort Matrix by Maximum Row element
- How to divide matrix rows in R by row median?
- Python – Sort row by K multiples
- Python – Sort Matrix by total characters
- Python – Sort Matrix by None frequency
- Python – Sort Matrix by Palindrome count
- Sort the matrix row-wise and column-wise using Python
- Python – Sort Matrix by Maximum String Length
- Find median in row wise sorted matrix in C++
- JavaScript Program to Find median in row wise sorted matrix
- Python – Sort Matrix by K Sized Subarray Maximum Sum
- How to divide the data frame row values in R by row median?
- How to find the row median of columns having same name in R matrix?
- Python Program to sort rows of a matrix by custom element count
- Python – Sort Matrix by Number of elements greater than its previous element

Advertisements