Python – Sort Matrix by Maximum String Length

PythonServer Side ProgrammingProgramming

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

 Live Demo

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.

raja
Published on 06-Sep-2021 08:13:55
Advertisements