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.