Sometimes, while working with Python records, we can have a problem in which we need to perform grouping of elements of tuple by similar Kth index element. This kind of problem can have application in web development domain. Let's discuss the certain way in which this task can be performed.
Input : test_list = [(4, 5), (3, 2), (2, 2), (1, 2), (5, 5)], K = 0
Output : [((1, 2), ), ((2, 2), ), ((3, 2), ), ((4, 5), ), ((5, 5), )]
Input : test_list = [(4, 5), (3, 2), (2, 2)], K = 1
Output : [((2, 2), (3, 2)), ((4, 5), )]
The combination of above functions can be used to solve this problem. In this, we perform the task of grouping the elements from Kth index extracted using itemgetter and generator expression is used to bind whole logic together.
Output : The original list is : [(4, 5), (3, 2), (2, 2), (1, 2), (5, 5)]
Tuples after grouping : [((1, 2), (2, 2), (3, 2)), ((4, 5), (5, 5))]
OutputThe original list is : [(4, 5), (3, 2), (2, 2), (1, 2), (5, 5)]
Tuples after grouping : [((4, 5), (5, 5)), ((3, 2), (2, 2), (1, 2))]
OutputThe original list is : [(4, 5), (3, 2), (2, 2), (1, 2), (5, 5)]
Tuples after grouping : [((4, 5), (5, 5)), ((3, 2), (2, 2), (1, 2))]
OutputThe original list is : [(4, 5), (3, 2), (2, 2), (1, 2), (5, 5)]
Tuples after grouping : [((4, 5), (5, 5)), ((3, 2), (2, 2), (1, 2))]