Python – Cross tuple summation grouping
Sometimes, while working with Python tuple records, we can have a problem in which we need to perform summation grouping of 1st element of tuple pair w.r.t similar 2nd element of tuple. This kind of problem can have application in day-day programming. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [(1, 5), (7, 4), (9, 6), (11, 6)]
Output : [(7, 4), (1, 5), (20, 6)]Input : test_list = [(1, 8)]
Output : [(1, 8)]
Method #1 : Using loop
This is brute force way in which this task can be performed. In this we check for similar second elements and perform summation till then and perform the accumulated grouping.
# Python3 code to demonstrate working of # Cross tuple summation grouping# Using loop # initializing listtest_list = [(4, 5), (7, 5), (8, 6), (10, 6), (10, 4), (6, 7), (3, 7)] # printing original listprint("The original list is : " + str(test_list)) # Concatenate Similar Key values# Using looptemp = dict()for ele1, ele2 in test_list: temp[ele2] = temp.get(ele2, 0) + ele1res = [(ele2, ele1) for (ele1, ele2) in temp.items()] # printing result print("The grouped records are : " + str(res)) |
The original list is : [(4, 5), (7, 5), (8, 6), (10, 6), (10, 4), (6, 7), (3, 7)] The grouped records are : [(10, 4), (11, 5), (18, 6), (9, 7)]
Method #2 : Using groupby() + sum() + zip() + list comprehension
The combination of above functions can be used to solve this problem. In this, we perform the task of finding sum using sum(). The task of grouping is done by groupby().
# Python3 code to demonstrate working of # Cross tuple summation grouping# Using groupby() + sum() + zip() + list comprehensionfrom itertools import groupby # initializing listtest_list = [(4, 5), (7, 5), (8, 6), (10, 6), (10, 4), (6, 7), (3, 7)] # printing original listprint("The original list is : " + str(test_list)) # Concatenate Similar Key values# Using groupby() + sum() + zip() + list comprehensionres = [(sum(next(zip(*ele))), key) for key, ele in groupby( test_list, key = lambda tup:tup[1])] # printing result print("The grouped records are : " + str(res)) |
The original list is : [(4, 5), (7, 5), (8, 6), (10, 6), (10, 4), (6, 7), (3, 7)] The grouped records are : [(10, 4), (11, 5), (18, 6), (9, 7)]
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


