Skip to content
Related Articles

Related Articles

Improve Article

Python – Elements frequency in Tuple Matrix

  • Last Updated : 03 Jul, 2020

Sometimes, while working with Python Tuple Matrix, we can have a problem in which we need to get frequency of each element in it. This kind of problem can occur in domains such as day-day programming and web development domain. Let’s discuss certain ways in which this problem can be solved.

Input : test_list = [[(4, 5), (3, 2)], [(2, 2)]]
Output : {4: 1, 5: 1, 3: 1, 2: 3}

Input : test_list = [[(4, 5), (3, 2)]]
Output : {4: 1, 5: 1, 3: 1, 2: 1}

Method #1 : Using nested chain() + "*" operator + Counter()
The combination of above functions can be used to solve this problem. In this, we perform the task of getting frequency using Counter() and nested chain to cater the nestings and “*” operator is used to perform unpacking and packing of each element.




# Python3 code to demonstrate working of 
# Elements frequency in Tuple Matrix
# Using nested chain() + "*" operator + Counter()
from itertools import chain
from collections import Counter
  
# initializing lists
test_list = [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Elements frequency in Tuple Matrix
# Using nested chain() + "*" operator + Counter()
res = dict(Counter(chain(*chain(*test_list))))
  
# printing result 
print("Elements frequency : " + str(res))
Output :



The original list is : [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]
Elements frequency : {4: 1, 5: 3, 3: 1, 2: 4, 1: 1}

 

Method #2 : Using chain.from_iterables() + Counter()
The combination of above functions can be used to solve this problem. In this, we perform the task of packing, unpacking and flattening using chain.from_iterables().




# Python3 code to demonstrate working of 
# Elements frequency in Tuple Matrix
# Using chain.from_iterables() + Counter()
from itertools import chain
from collections import Counter
  
# initializing lists
test_list = [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Elements frequency in Tuple Matrix
# Using chain.from_iterables() + Counter()
res = dict(Counter(chain.from_iterable(chain.from_iterable(test_list))))
  
# printing result 
print("Elements frequency : " + str(res))
Output :
The original list is : [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]
Elements frequency : {4: 1, 5: 3, 3: 1, 2: 4, 1: 1}

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :