Example:
tuple = ("python", "includehelp", 43, 54.23)
Assigning frequency to Tuples
In our program, we have a list of tuples and we need to count the number of tuples and then assign the frequency to the last value of the tuple.
Input:
tupList = [(4, 1), (3, 3), (4, 1), (5, 7), (3, 3), (4, 1)]
Output:
freqList = [((4, 1), 3), ((3, 3), 2), ((4, 1), 2)]
To perform the given task in python, we have multiple methods as we just need to count the number of occurrences of each tuple and then add it as the last element for the tuple.
Let's see different methods to perform the task in Python.
Method 1:
One method to solve the problem is by counting the occurrence of each tuple in the list using the counter() method then this frequency is fetched using the items() method. Using the list comprehension and * operator, we will initialize tuple list with frequency.
Program to assign the frequency to tuples in Python
Output:
Note: We can use the most_common() method instead of the items() method to count the tuples.
need an explanation for this answer? contact us directly to get an explanation for this answer