Q:

Python program to assign frequency to tuples

belongs to collection: Python Tuple Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

# Python program to assign frequency
# to tuples

from collections import Counter

# Creating and printing the list of tuple
tupList = [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
print("The list of Tuples is : " + str(tupList))

# Counting occurences and adding it to the tuples
freqTuple = [(key, val) for key, val in Counter(tupList).items()]

# Printing results
print("List of tuples with frequency added at end :" + str(freqTuple))

Output:

The list of Tuples is : [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9,), (2, 7)]
List of tuples with frequency added at end :[((6, 5, 8), 3), ((2, 7), 2), ((9,), 1)]

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

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to check if any list element is pre... >>
<< Python program to remove tuples from the list havi...