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

When sorting rows of a matrix based on custom element count, we can define a helper function that counts how many elements from each row match our custom criteria. This approach uses list comprehension with the len() method to determine the sort order.

Example

Let's sort matrix rows by counting how many elements from each row appear in our custom list ?

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]]

How It Works

The sorting process works as follows:

  • Row [31, 5, 22, 7]: Contains 2 custom elements (31, 7)
  • Row [85, 5]: Contains 1 custom element (85)
  • Row [9, 11, 22]: Contains 0 custom elements
  • Row [7, 48]: Contains 1 custom element (7)

The rows are sorted in ascending order by count: 0, 1, 1, 2.

Alternative Approach Using Lambda

We can achieve the same result using a lambda function ?

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

my_list.sort(key=lambda row: len([element for element in row if element in custom_list]))

print("Sorted matrix:")
print(my_list)
Sorted matrix:
[[9, 11, 22], [85, 5], [7, 48], [31, 5, 22, 7]]

Conclusion

Use the sort() method with a custom key function to sort matrix rows by element count. The key function counts matching elements using list comprehension and returns the count for sorting.

Updated on: 2026-03-26T00:50:49+05:30

264 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements