Sunday, November 17, 2024
Google search engine
HomeLanguagesPython – Group Tuples by Kth Index Element

Python – Group Tuples by Kth Index Element

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




# Python3 code to demonstrate working of
# Group Tuples by Kth Index Element
# Using groupby() + itemegetter() + generator expression
from operator import itemgetter
from itertools import groupby
 
# initializing lists
test_list = [(4, 5), (3, 2), (2, 2), (1, 2), (5, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 1
 
# Group Tuples by Kth Index Element
# Using groupby() + itemegetter() + generator expression
test_list.sort()
res = list(tuple(sub) for idx, sub in groupby(test_list, key = itemgetter(K)))
 
# printing result
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




# Python3 code to demonstrate working of
# Group Tuples by Kth Index Element
 
# initializing lists
test_list = [(4, 5), (3, 2), (2, 2), (1, 2), (5, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
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)
 
# printing result
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:

  1. Import the defaultdict from the collections module.
  2. Create a defaultdict with a list as its default value.
  3. Loop through the tuples in the test_list, and append them to the dictionary with their Kth index element as the key.
  4. Convert the values of the dictionary into tuples and append them to the result list.
  5. Print the original list and the result list.

Python3




# importing defaultdict from collections module
from collections import defaultdict
 
# initializing lists
test_list = [(4, 5), (3, 2), (2, 2), (1, 2), (5, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 1
 
# creating defaultdict with list as default value
d = defaultdict(list)
 
# looping through the tuples in the test_list and appending them to the dictionary with their Kth index element as the key
for t in test_list:
    d[t[K]].append(t)
 
# converting the values of the dictionary into tuples and appending them to the result list
res = [tuple(v) for v in d.values()]
 
# printing result
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




# initializing lists
test_list = [(4, 5), (3, 2), (2, 2), (1, 2), (5, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 1
 
# creating an empty dictionary to store the grouped tuples
d = {}
 
# looping through the tuples in the test_list and grouping them based on the Kth index element
for t in test_list:
    if t[K] in d:
        d[t[K]].append(t)
    else:
        d[t[K]] = [t]
 
# converting the values of the dictionary into tuples and appending them to the result list
res = [tuple(v) for v in d.values()]
 
# printing result
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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments