Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Record Similar tuple occurrences in Python
When it is required to record similar tuple occurrences, the 'map' method, the 'Counter' method and the 'sorted' method can be used.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuple basically contains tuples enclosed in a list.
The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.
The 'sorted' method is used to sort the elements of a list.
The 'Counter' is a sub-class that helps count hashable objects, i.e it creates a hash table on its own (of an iterable- like a list, tuple, and so on) when it is invoked.
It returns an itertool for all of the elements with a non-zero value as the count.
Below is a demonstration of the same −
Example
from collections import Counter
my_list_1 = [(11, 14), (0, 78), (33, 67), (89, 0)]
print("The list of tuple is : ")
print(my_list_1)
my_result = dict(Counter(tuple(elem) for elem in map(sorted, my_list_1)))
print("The frequency of like tuples is : ")
print(my_result)
Output
The list of tuple is :
[(11, 14), (0, 78), (33, 67), (89, 0)]
The frequency of like tuples is :
{(11, 14): 1, (0, 78): 1, (33, 67): 1, (0, 89): 1}
Explanation
The required packages are imported.
- A list of tuple is defined and is displayed on the console.
- The 'Counter' method is used on this list of tuple, and it is applied to every element using the 'map' method.
- This is then converted into a dictionary.
- This output is assigned to a value.
- It is displayed on the console.
