- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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 total characters
When it is required to sort matrix by total characters, a method is defined that uses list comprehension and the ‘sum’ and ‘len’ methods to determine the result.
Below is a demonstration of the same −
def total_characters(row): return sum([len(element) for element in row]) my_list = [["pyt", "is", "fun"], ["python", "fun"],["py", "4", "good"], ["python"]] print("The list is :") print(my_list) my_list.sort(key=total_characters) print("The result is :") print(my_list)
The list is : [['pyt', 'is', 'fun'], ['python', 'fun'], ['py', '4', 'good'], ['python']] The result is : [['python'], ['py', '4', 'good'], ['pyt', 'is', 'fun'], ['python', 'fun']]
A method named ’total_characters’ is defined that takes row as a parameter, and returns sum of the elements as output.
This is done by iterating over the elements using list comprehension and getting length of every element and adding these lengths.
Outside the method, a list is defined and displayed on the console.
The list is sorted and the method is called by passing the required parameter.
This result is assigned to a variable.
This is the output that is displayed on the console.
- Sort Tuples by Total digits in Python
- Python – Sort Tuples by Total digits
- Python – Sort Matrix by Row Median
- Python - Sort Matrix by Maximum Row element
- Python – Sort Matrix by None frequency
- Python – Sort Matrix by Palindrome count
- Python – Sort Matrix by Maximum String Length
- Sort Characters By Frequency in C++
- Python – Sort Matrix by K Sized Subarray Maximum Sum
- Python Program to sort rows of a matrix by custom element count
- Python – Sort Matrix by Number of elements greater than its previous element
- Python Program to Sort Matrix Rows by summation of consecutive difference of elements
- Python program to Sort a List of Strings by the Number of Unique Characters
- Column Sort of a Matrix in Python
- Sort Array By Parity in Python