Example:
tuple = ("python", "includehelp", 43, 54.23)
List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of ordered set of values enclosed in square brackets [].
Example:
list = [3 ,1, 5, 7]
List of tuples is a list whose each element is a tuple.
Example:
tupList = [("python", 7), ("learn" , 1), ("programming", 7), ("code" , 3)]
Restricting tuples by frequency of first element's value in a tuple list
We need to restrict the frequency of occurrence of tuple's first value to K. For this, we will be keeping a check on the count of occurrence of the first value of tuples and discard values where the count exceeds K.
For this we have multiple methods in Python,
Input:
[(1, 7), (6, 4), (3, 5), (1, 4), (7, 3), (3, 7)] k = 1
Output:
[(1, 7), (6, 4), (3, 5), (7, 3)]
Method 1:
A method to solve the problem is by using a dictionary to count the occurrence of the first element of the tuple and accept the value if it is smaller than or equal to K, otherwise discard it. Then print the resultant list.
Program:
Output:
Method 2:
An alternate way is to use the default dictionary for the value count and using the filter method to filter out values with frequency larger than K.
Program:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer