
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract Rows of a Matrix with Even Frequency Elements in Python
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.
Advertisements