- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Test if Rows have Similar frequency
When it is required to check if rows have similar frequency, the ‘all’ operator, the ‘Counter’ method and a simple iteration is used.
Below is a demonstration of the same −
Example
from collections import Counter my_list = [[21, 92, 64, 11, 3], [21, 3, 11, 92, 64], [64, 92, 21, 3, 11]] print("The list is :") print(my_list) my_result = all(dict(Counter(row)) == dict(Counter(my_list[0])) for row in my_list ) if(my_result == True): print("All rows have similar frequency") else: print("All rows do not have similar frequency")
Output
The list is : [[21, 92, 64, 11, 3], [21, 3, 11, 92, 64], [64, 92, 21, 3, 11]] All rows have similar frequency
Explanation
The required packages are imported into the environment.
A list of list with integers is defined and is displayed on the console.
The list in the list of list is converted to a Counter and then to a dictionary.
It is checked to see if elements in every list occur at the same frequency.
If yes, a Boolean value is stored in a variable.
Depending on this Boolean variable, relevant message is displayed on the console.
Advertisements