Python – Group Tuples by Kth Index Element
Last Updated :
05 Apr, 2023
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), )]
Method 1: Using groupby() + itemegetter() + generator expression
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.
Python3
from operator import itemgetter
from itertools import groupby
test_list = [( 4 , 5 ), ( 3 , 2 ), ( 2 , 2 ), ( 1 , 2 ), ( 5 , 5 )]
print ("The original list is : " + str (test_list))
K = 1
test_list.sort()
res = list ( tuple (sub) for idx, sub in groupby(test_list, key = itemgetter(K)))
print ("Tuples after grouping : " + str (res))
|
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))]
Method 2: Using in, not in operators and for loops
Python3
test_list = [( 4 , 5 ), ( 3 , 2 ), ( 2 , 2 ), ( 1 , 2 ), ( 5 , 5 )]
print ( "The original list is : " + str (test_list))
K = 1
x = []
res = []
for i in test_list:
if i[K] not in x:
x.append(i[K])
for i in x:
p = []
for j in test_list:
if (j[K] = = i):
p.append(j)
p = tuple (p)
res.append(p)
print ( "Tuples after grouping : " + str (res))
|
Output
The 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))]
Method 2: Using in, not in operators and for loops
Steps:
- Import the defaultdict from the collections module.
- Create a defaultdict with a list as its default value.
- Loop through the tuples in the test_list, and append them to the dictionary with their Kth index element as the key.
- Convert the values of the dictionary into tuples and append them to the result list.
- Print the original list and the result list.
Python3
from collections import defaultdict
test_list = [( 4 , 5 ), ( 3 , 2 ), ( 2 , 2 ), ( 1 , 2 ), ( 5 , 5 )]
print ( "The original list is : " + str (test_list))
K = 1
d = defaultdict( list )
for t in test_list:
d[t[K]].append(t)
res = [ tuple (v) for v in d.values()]
print ( "Tuples after grouping : " + str (res))
|
Output
The 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))]
Time Complexity: O(n), where n is the length of the test_list.
Auxiliary Space: O(n), where n is the length of the test_list.
Method 4: Using a dictionary and a for loop:
Step-by-step approach:
- Initialize the list of tuples and print it.
- Initialize the K value.
- Create an empty dictionary to store the grouped tuples.
- Loop through the tuples in the test_list and group them based on the Kth index element using an if-else statement.
- If the key already exists in the dictionary, append the tuple to the list of tuples associated with that key.
- Otherwise, create a new key-value pair with the key as the Kth index element and the value as a list containing the tuple.
- Convert the values of the dictionary into tuples using list comprehension and the tuple function.
- Print the result.
Below is the implementation of the above approach:
Python3
test_list = [( 4 , 5 ), ( 3 , 2 ), ( 2 , 2 ), ( 1 , 2 ), ( 5 , 5 )]
print ( "The original list is : " + str (test_list))
K = 1
d = {}
for t in test_list:
if t[K] in d:
d[t[K]].append(t)
else :
d[t[K]] = [t]
res = [ tuple (v) for v in d.values()]
print ( "Tuples after grouping : " + str (res))
|
Output
The 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))]
Time Complexity: O(n) because it loops through the n tuples in the test_list once.
Auxiliary Space: O(n) because it creates a dictionary with n key-value pairs, where each value is a list of tuples.
Similar Reads
Python | Binary Group Tuple list elements
Sometimes, while working with tuples, we can have problems of grouping them, be it based on gender or any particular binary category. This can have applications in many domains. Let's discuss certain ways in which this can be performed. Method #1 : Using generator + loop + zip() The brute force meth
4 min read
Python - Element Index in Range Tuples
Sometimes, while working with Python data, we can have a problem in which we need to find the element position in continuous equi ranged tuples in list. This problem has applications in many domains including day-day programming and competitive programming. Let's discuss certain ways in which this t
6 min read
Python - Filter Tuples by Kth element from List
Given a list of tuples, filter by Kth element presence in List. Input : test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)], check_list = [4, 2, 3, 10], K = 2 Output : [('is', 4, 3)] Explanation : 3 is 2nd element and present in list, hence filtered tuple. Input : test_list = [("GFg", 5, 9),
5 min read
Python | Binary element list grouping
Sometimes while working with the databases, we need to perform certain list operations that are more like query language, for instance, grouping of nested list element with respect to its other index elements. This article deals with binary nested list and group each nested list element with respect
9 min read
Python - Closest Pair to Kth index element in Tuple
In the given problem, condition K specifies the maximum allowable difference between corresponding elements of tuples, i.e., it represents the proximity threshold for finding the nearest tuple. The goal is to find the tuple in the list whose elements have the smallest maximum difference compared to
7 min read
Python - Group records by Kth column in List
Sometimes, while working with Python lists, we can have a problem in which we need to perform grouping of records on basis of certain parameters. One such parameters can be on the Kth element of Tuple. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + defaultdic
8 min read
Python - Group Records on Similar index elements
Sometimes, while working with Python records, we can have a problem in which we need to perform grouping of particular index of tuple, on basis of similarity of rest of indices. This type of problems can have possible applications in Web development domain. Let's discuss certain ways in which this t
6 min read
Python - Group Elements in Matrix
Given a Matrix with two columns, group 2nd column elements on basis of 1st column. Input : test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [2, 9]] Output : {5: [8, 4], 2: [0, 3, 9]} Explanation : 8 and 4 are mapped to 5 in Matrix, all others to 2. Input : test_list = [[2, 8], [2, 0], [2, 4], [2, 3], [2
6 min read
Python - Elements frequency in Tuple
Given a Tuple, find the frequency of each element. Input : test_tup = (4, 5, 4, 5, 6, 6, 5) Output : {4: 2, 5: 3, 6: 2} Explanation : Frequency of 4 is 2 and so on.. Input : test_tup = (4, 5, 4, 5, 6, 6, 6) Output : {4: 2, 5: 2, 6: 3} Explanation : Frequency of 4 is 2 and so on.. Method #1 Using def
7 min read
Python | Get Kth element till N
Sometimes, we may come across a utility in which we require to get the first N sublist elements that too only a particular index. This can have an application in queuing to get only the Kth N personâs name. Letâs discuss certain ways in which this can be done. Method #1 : Using list comprehension an
3 min read