Python – Sort Matrix by total characters

PythonServer Side ProgrammingProgramming

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 −

Example

 Live Demo

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)

Output

The list is :
[['pyt', 'is', 'fun'], ['python', 'fun'], ['py', '4', 'good'], ['python']]
The result is :
[['python'], ['py', '4', 'good'], ['pyt', 'is', 'fun'], ['python', 'fun']]

Explanation

  • 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.

raja
Updated on 06-Sep-2021 07:59:10

Advertisements