- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Grouped summation of tuple list in Python
When it is required to find the grouped summation of a list of tuple, the 'Counter' method and the '+' operator need to be used.
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.
The '+' operator can be used to add numeric values or concatenate strings.
Below is a demonstration for the same −
from collections import Counter my_list_1 = [('Hi', 14), ('there', 16), ('Jane', 28)] my_list_2 = [('Jane', 12), ('Hi', 4), ('there', 21)] print("The first list is : ") print(my_list_1) print("The second list is : " ) print(my_list_2) cumulative_val_1 = Counter(dict(my_list_1)) cumulative_val_2 = Counter(dict(my_list_2)) cumulative_val_3 = cumulative_val_1 + cumulative_val_2 my_result = list(cumulative_val_3.items()) print("The grouped summation of list of tuple is : ") print(my_result)
The first list is : [('Hi', 14), ('there', 16), ('Jane', 28)] The second list is : [('Jane', 12), ('Hi', 4), ('there', 21)] The grouped summation of list of tuple is : [('Hi', 18), ('there', 37), ('Jane', 40)]
- The required packages are imported.
- Two list of tuples are defined, and are displayed on the console.
- Both of these list of tuples are converted to dictionaries.
- They are added using the '+' operator.
- This result is converted to a list, by using only the 'values' of the dictionary.
- This operation's data is stored in a variable.
- This variable is the output that is displayed on the console.
- Python Grouped summation of tuple list¶
- Summation of list as tuple attribute in Python
- Python Grouped Flattening of list
- Python – Dual Tuple Alternate summation
- Summation of tuples in list in Python
- Alternate element summation in list (Python)
- Flatten tuple of List to tuple in Python
- Why python returns tuple in list instead of list in list?
- Python - Column summation of tuples
- Dictionary to list of tuple conversion in Python
- Python - Ways to iterate tuple list of lists
- Convert a list into tuple of lists in Python
- Maximum element in tuple list in Python
- Extract digits from Tuple list Python
- Combinations of sum with tuples in tuple list in Python