Python Program to sort rows of a matrix by custom element count


When it is required to sort rows of a matrix by custom element count, a method is defined that uses the list comprehension and ‘len’ method to find the output.

Below is a demonstration of the same −

Example

 Live Demo

def get_count_matrix(my_key):
   return len([element for element in my_key if element in custom_list])

my_list = [[31, 5, 22, 7], [85, 5], [9, 11, 22], [7, 48]]

print("The list is :")
print(my_list)

custom_list = [31, 85, 7]

my_list.sort(key=get_count_matrix)

print("The resultant list is :")
print(my_list)

Output

The list is :
[[31, 5, 22, 7], [85, 5], [9, 11, 22], [7, 48]]
The resultant list is :
[[9, 11, 22], [85, 5], [7, 48], [31, 5, 22, 7]]

Explanation

  • A method named ‘get_count_matrix’ is defined that takes a key as a parameter.

  • It uses list comprehension to iterate over the list and checks if the specific key is present in the element.

  • If yes, its length is returned using the ‘len’ method.

  • Outside the method, a list of list is defined and is displayed on the console.

  • Another list with integers is defined.

  • The list is sorted using the ‘sort’ method, and specifying the key as the previously defined method.

  • This list is displayed as output on the console.

Updated on: 04-Sep-2021

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements