Python – Restrict Elements Frequency in List

PythonServer Side ProgrammingProgramming

When it is required to restrict elements frequency in a list, a simple iteration is used along with the ‘append’ method.

Example

Below is a demonstration of the same −

from collections import defaultdict

my_list = [11, 14, 15,14, 11, 14, 14, 15, 15, 16]

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

my_dict = {14 : 3, 11 : 1, 16 : 1, 15 : 2}

print("The dictionary is :")
print(my_dict)

my_result = []
my_def_dict = defaultdict(int)
for element in my_list:
   my_def_dict[element] += 1

   if my_def_dict[element] > my_dict[element]:
      continue
   else:
      my_result.append(element)

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

Output

The list is :
[11, 14, 15, 14, 11, 14, 14, 15, 15, 16]
The restrict dictionary is :
{14: 3, 11: 1, 16: 1, 15: 2}
The result is :
[11, 14, 15, 14, 14, 15, 16]

Explanation

  • The required packages are imported into the environment.

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

  • A dictionary is defined and displayed on the console.

  • An empty list is defined.

  • A default dictionary of integers is defined.

  • The original list is iterated over, and the dictionary elements are incremented by 1.

  • Depending on whether the element in the original dictionary and default dictionary are greater or not, the ‘continue’ operator is used.

  • Then, the ‘append’ method is used to add the element to the empty list.

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

raja
Published on 08-Sep-2021 08:22:12
Advertisements