Python – Fractional Frequency of elements in List

PythonServer Side ProgrammingProgramming

When it is required to find the fractional frequency of elements in a list, a dictionary comprehension, a simple iteration and the ‘Counter’ method is used.

Example

Below is a demonstration of the same −

from collections import Counter

my_list = [14, 15, 42, 60, 75, 50, 45, 55, 14, 60, 48, 65]

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

my_num = {index : 0 for index in set(my_list)}

my_denominator = Counter(my_list)

my_result = []
for element in my_list:

   my_num[element] += 1
   my_result.append(str(my_num[element]) + '/' + str(my_denominator[element]))

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

Output

The list is :
[14, 15, 42, 60, 75, 50, 45, 55, 14, 60, 48, 65]
The result is :
['1/2', '1/1', '1/1', '1/2', '1/1', '1/1', '1/1', '1/1', '2/2', '2/2', '1/1', '1/1']

Explanation

  • The required packages are imported into the environment.

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

  • A dictionary comprehension is used to get unique elements from the list.

  • This is assigned to a variable.

  • A counter is created from the list.

  • An empty list is defined.

  • The list is iterated over, and the ‘/’ operator is used to add specific elements to the empty list using ‘append’ method.

  • This is the output that is displayed on the console.

raja
Published on 08-Sep-2021 08:24:52
Advertisements