Python | Divide the list into unequal groups

Python Methods and Functions

Method: Using itertools.islice () + List Comprehension
A combination of the above functions can be used to accomplish this task. In this, islice () is used to perform the main task of slicing a list, and a list comprehension is used to accomplish the task of linking logic and iterations. The container is converted to an iterator for faster iteration.

# Python3 code to demonstrate how it works
# Split the list into unequal groups
# using itertools.islice () + list comprehension

from itertools import islice

 
# initialize the list

test_list = [ 1 , 4 , 5 , 7 , 6 , 5 , 4 , 2 , 10 ]

 
# initialize split list

split_list = [ 3 , 4 , 2 ]

 
# print original list

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

 
# print split list

print ( "The split list is:" + str (split_list))

 
# Split the list into unequal groups
# using itertools.islice ( ) + list comprehension

temp = iter (test_list)

res = [ list (islice (temp, 0 , ele)) for ele   in split_list]

 
# print result

print ( "The resultant split list is:" + str (res))

Output:

 The original list is: [1, 4, 5, 7, 6, 5, 4, 2, 10] The split list is: [3, 4, 2] The resultant split list is: [[1, 4, 5], [7, 6, 5, 4], [2, 10]] 




Tutorials