
- 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 Maximum String Length
When it is required to sort matrix by maximum string length, a method is defined that takes a list as parameter and uses list comprehension and the ‘max’ and ‘len’ methods to determine the result.
Below is a demonstration of the same −
Example
def max_length(row): return max([len(element) for element in row]) my_matrix = [['pyt', 'fun'], ['python'], ['py', 'cool'], ['py', 'ea']] print("The matrix is :") print(my_matrix ) my_matrix .sort(key=max_length) print("The result is :") print(my_matrix )
Output
The matrix is : [['pyt', 'fun'], ['python'], ['py', 'cool'], ['py', 'ea']] The result is : [['py', 'ea'], ['pyt', 'fun'], ['py', 'cool'], ['python']]
Explanation
A method named ‘max_length’ is defined that takes a list as a parameter, and gets the length of every element and uses ‘max’ to get the length of longest element.
Outside the method, a list of list is defined and is displayed on the console.
The list is sorted by specifying the method which was previously defined.
This is the output that is displayed on the console.
- Related Questions & Answers
- Python – Sort Matrix by K Sized Subarray Maximum Sum
- Python - Sort Matrix by Maximum Row element
- Python – Sort Matrix by total characters
- Python – Sort Matrix by Row Median
- Python – Sort Matrix by None frequency
- Python – Sort Matrix by Palindrome count
- Python – Sort by Maximum digit in Element
- Python – Sort String list by K character frequency
- Python – Sort by range inclusion
- Python – Sort by Uppercase Frequency
- Python – Sort Dictionaries by Size
- Python – Convert Integer Matrix to String Matrix
- Python – Sort Matrix by Number of elements greater than its previous element
- Python – Sort row by K multiples
- Python – Sort Tuples by Total digits
Advertisements