Python Program to Extract Rows of a matrix with Even frequency Elements


When it is required to extract rows of a matrix with even frequency elements, a list comprehension with ‘all’ operator and ‘Counter’ method are used.

Example

Below is a demonstration of the same

from collections import Counter

my_list = [[41, 25, 25, 62], [41, 41, 41, 41, 22, 22], [65, 57, 65, 57], [11, 24, 36, 48]]

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

my_result = [sub for sub in my_list if all( value % 2 == 0 for key, value in
list(dict(Counter(sub)).items()))]

print("The result is :")
print(my_result)

Output

The list is :
[[41, 25, 25, 62], [41, 41, 41, 41, 22, 22], [65, 57, 65, 57], [11, 24, 36, 48]]
The result is :
[[41, 41, 41, 41, 22, 22], [65, 57, 65, 57]]

Explanation

  • A list of list is defined and is displayed on the console.

  • A list comprehension is used to iterate over the elements in the list, and the ‘all’ operator is used, to check if the value is divisibe by 2.

  • The elements of the list are accessed using ‘Counter’ and ‘dict’.

  • This is converted to a list and is assigned to a variable.

  • This is displayed as output on the console.

Updated on: 16-Sep-2021

145 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements