Python | Group a tuple into a list based on value

Python Methods and Functions

Method # 1: Using itemgetter () + list comprehension + groupby()

A combination of the above functions can be used to accomplish this task. In this we access the value using itemgetter () and the logic for grouping is done using groupby () and a list comprehension.

# Python3 code to demonstrate how it works
# Group tuple into a list based on value
# using itemgetter () + list comprehension + groupby ()

from operator import itemgetter

from itertools import groupby

  
# initialize the list

test_list  = [( 1 , 4 ), ( 2 , 4 ), ( 6 , 7 ), ( 5 , 1 ), ( 6 , 1 ), ( 8 , 1 )]

 
# print original list

print ( "The original list:" + < code class = "functions"> str (test_list))

 
# Group tuple into a list based on value
# using itemgetter () + list comprehension + groupby ()

res = [[i for i, j in temp]

for key, temp in groupby (test_list, key = itemgetter ( 1 ))]

  
# print result

print < code class = "plain"> ( "The list after grouping by value:" + str (res))

Output:

 The original list: [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)] The list after grouping by value: [[1, 2], [6], [5, 6, 8]] 

Method # 2: Using map () + itemgetter () + groupby () + list comprehension

This method is the same as above, with the only difference that we chose a map for generating keys as a nested list for generating new resulting lists.

# Python3 code to demonstrate how it works
# Group tuple into a list based on value
# using m ap () + itemgetter () + groupby () + list comprehension

from operator import itemgetter

from itertools import groupby

 
# initialize the list

test_list = [( 1 , 4 ), ( 2 , 4 ), ( 6 , 7 ), ( 5 , 1 < / code> ), ( 6 , 1 ), ( 8 , 1 )]

 
# print original list

print ( "The original list:" + str (test_list))

 
# Group tuple into a list based on value
# using map () + itemgetter () + groupby () + list comprehension

res = [ list ( map (itemgetter ( 0 ), temp)) 

for (key, temp) in groupby (test_list, itemgetter ( 1 ))]

 
# print result

print ( " The list after grouping by value: " + str (res))

Output:

 The original list : [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)] The list after grouping by value: [[1, 2 ], [6], [5, 6, 8]] 




Get Solution for free from DataCamp guru