Python - Restrict Tuples by frequency of first element’s value

PythonServer Side ProgrammingProgramming

When it is required to restrict the tuples by frequency of first element’s value, a simple ‘if’ condition along with an iteration and ‘append’ method is used.

Example

Below is a demonstration of the same

my_list = [(21, 24), (13, 42), (11, 23), (32, 43), (25, 56),(73, 84), (91, 40), (40, 83), (13, 27)]

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

my_key = 1

my_result = []
mems = dict()
for sub in my_list:

   if sub[0] not in mems.keys():
      mems[sub[0]] = 1
   else:
      mems[sub[0]] += 1
   if mems[sub[0]] <= my_key:
      my_result.append(sub)

print("The filtered tuples are :")
print(my_result)

Output

The list is :
[(21, 24), (13, 42), (11, 23), (32, 43), (25, 56), (73, 84), (91, 40), (40, 83), (13, 27)]
The filtered tuples are :
[(21, 24), (13, 42), (11, 23), (32, 43), (25, 56), (73, 84), (91, 40), (40, 83)]

Explanation

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

  • An integer value is assigned to 1.

  • An empty list is defined.

  • An empty dictionary is created.

  • The list of tuple is iterated over, and if an element is not found in the key value of the dictionary, the 0th index is assigned to 1.

  • Otherwise, it is incremented by 1.

  • If it is less than or equal to the key, the element is appended to the empty result.

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

raja
Published on 15-Sep-2021 11:53:15
Advertisements