To solve the problem, we need to group the keys based on the summation for the given condition. For this, we will be using list comprehension to perform summation of keys of groups created using a loop.
from collections import defaultdict
# Creating and printing the List
test_list = [(32, 'A', 'Python'), (35, 'A', 'Python'), (12, 'B', 'C programming language')]
print("The initial List of tuples is : " + str(test_list))
# Creating grouping and summation index lists
groupingIndex = [1, 2]
sumIndex = [0]
# Performing grouping summation
defDict = defaultdict(int)
for sub in test_list:
defDict[(sub[groupingIndex[0]], sub[groupingIndex[1]])] += sub[sumIndex[0]]
keyGrouping = [key + (val, ) for key, val in defDict.items()]
# Printing result
print("The list after Performing multiple keys grouped summation is : " + str(keyGrouping))
Output:
The initial List of tuples is : [(32, 'A', 'Python'), (35, 'A', 'Python'), (12, 'B', 'C programming language')]
The list after Performing multiple keys grouped summation is : [('A', 'Python', 67), ('B', 'C programming language', 12)]
Performing Multiple Keys Grouped Summation
To solve the problem, we need to group the keys based on the summation for the given condition. For this, we will be using list comprehension to perform summation of keys of groups created using a loop.
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer