Python – Cumulative Row Frequencies in a List

PythonServer Side ProgrammingProgramming

When it is required to get the cumulative row frequencies in a list, the ‘Counter’ method, and a list comprehension are used.

Example

Below is a demonstration of the same

from collections import Counter

my_list = [[11, 2, 32, 4, 31], [52, 52, 3, 71, 71, 3], [1, 3], [19, 19, 40, 40, 40]]

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

my_element_list = [19, 2, 71]

my_frequency = [Counter(element) for element in my_list]

my_result = [sum([freq[word] for word in my_element_list if word in freq]) for freq in my_frequency]

print("The resultant matrix is :")
print(my_result)

Output

The list is :
[[11, 2, 32, 4, 31], [52, 52, 3, 71, 71, 3], [1, 3], [19, 19, 40, 40, 40]]
The resultant matrix is :
[1, 2, 0, 2]

Explanation

• The required packages are imported into the environment.

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

• Another list of integers is defined.

• The list comprehension along with the ‘Counter’ method is used to iterate through the list.

• This is assigned to a variable.

• List comprehension is used to iterate through the list again and add the elements if the element is present in the list.

• This is assigned to a variable.

• This is displayed as output on the console.

Published on 14-Sep-2021 10:24:20
Advertisements