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

PythonServer Side ProgrammingProgramming

Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

Practical Data Science using Python

22 Lectures 6 hours

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 10:42:37