Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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. This technique allows you to sort rows based on the combined length of all strings in each row.
Example
The following example demonstrates sorting a matrix by total characters ?
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']]
How It Works
The sorting process follows these steps:
- The
total_charactersfunction calculates the total character count for each row by summing the lengths of all elements - List comprehension iterates through each element in the row and applies
len()to get character counts - The
sort()method uses the function as a key to determine sorting order - Rows are arranged in ascending order based on their total character count
Alternative Using Lambda
You can achieve the same result using a lambda function ?
my_list = [["pyt", "is", "fun"], ["python", "fun"], ["py", "4", "good"], ["python"]]
print("Original list:")
print(my_list)
my_list.sort(key=lambda row: sum(len(element) for element in row))
print("Sorted by total characters:")
print(my_list)
Original list: [['pyt', 'is', 'fun'], ['python', 'fun'], ['py', '4', 'good'], ['python']] Sorted by total characters: [['python'], ['py', '4', 'good'], ['pyt', 'is', 'fun'], ['python', 'fun']]
Conclusion
Sorting matrices by total characters is accomplished using a custom key function that calculates the sum of string lengths in each row. This approach provides flexible sorting based on character count rather than alphabetical order.
Advertisements
