Change language

Python | Split a tuple into groups of n

|

Method # 1: Using the enumeration and range function

# Python code for demonstration
# how to split a tuple
# into a group of k-tuples

  
# initializing tuple

ini_tuple = ( 1 , 2 , 3 , 4 , 8 , 12 , 3 , 34 ,

67 , 45 , 1 , 1 , 43 , 65 , 9 , 10 )

 
# print the original tuple

print ( "initial list" , str (ini_tuple))

 
# code for the group
# tuple to court hedgehog 4 sizes

res = tuple (ini_tuple [x: x + 4

for x in range ( 0 , len (ini_tuple), 4 ))

 
# print result

print ( "resultant tuples" , str ( res))

Exit:

initial list (1, 2, 3, 4, 8, 12, 3, 34, 67, 45 , 1, 1, 43, 65, 9, 10)
resultant tuples ((1, 2, 3, 4), (8, 12, 3, 34), (67, 45, 1, 1), (43, 65, 9, 10))

Method # 2: Using the enumeration and the mode operator

# Python code for demonstration
# how to split a tuple
# to a group of k-tuples

  
# initializing tuple

ini_tuple = ( 1 , 2 , 3 , 4 , 8 , 12 , 3 , 34 ,

67 , 45 , 1 , 1 , 43 , 65 , 9 , 10 )

 
# print the original tuple

print ( "initial list" ,   str (ini_tuple))

 
# code for the group
# tuple in a tuple of 4 sizes

res = tuple (ini_tuple [n: n + 4 ] for n, i in enumerate (ini_tuple)

if n % 4 = = 0 )

 
# print result

print ( " resultant tuples " , str (res))

Exit:

initial list (1, 2, 3, 4, 8, 12, 3, 34, 67, 45, 1, 1, 43, 65, 9, 10)
resultant tuples ((1, 2, 3, 4), (8, 12, 3, 34), (67, 45, 1, 1), (43, 65, 9, 10))

Method # 3: Using itertools Recipes

# Python code for demo
# how to split a tuple
# into a group of k-tuples

  
# function to group a tuple into groups of 4

def grouper (n, iterable):

args = [ iter (iterable)] * n

return zip ( * args)

 

 
# initializing tuple

ini_tuple = ( 1 , 2 , 3 , 4 , 8 , 12 , 3 , 34 ,

67 , 45 , 1 , 1 , 43 , 65 , 9 , 10 )

 
# print the original tuple

print ( "initial list" , str (ini_tuple))

  
# code for the group
# tuple in 4 tuple sizes

res = tuple (grouper ( 4 , ini_tuple))

 
# print result

print ( "resultant tuples" , str (res))

Exit :

initial list (1, 2, 3, 4, 8, 12, 3, 34, 67, 45, 1, 1, 43 , 65, 9, 10)
resultant tuples ((1, 2, 3, 4), (8, 12, 3, 34), (67, 45, 1, 1), ( 43, 65, 9, 10))