CPU
CPU

Reputation: 287

How to Split or break a Python list into Unequal chunks, with specified chunk sizes

I have two Python lists of numbers.

list1 = [123,452,342,533,222,402,124,125,263,254,44,987,78,655,741,165,597,26,15,799,100,154,122,563]  
list2 = [2,5,14,3] ##these numbers specify desired chunk sizes  

I would like to create subsets or sub-lists of list1 by splitting list1 according to the size numbers in list2. As a result, I would like to have this:

a_list = [123,452] ##correspond to first element (2) in list2; get the first two numbers from list1  
b_list = [342,533,222,402,124] ##correspond to second element (5) in list2; get the next 5 numbers from list1  
c_list = [125,263,254,44,987,78,655,741,165,597,26,15,799,100] ##next 14 numbers from list1  
d_list = [154,122,563] ##next 3 numbers from list1  

Essentially, each chunk should follow list2. This means, the first chunk should have the first 2 elements from list1, the second chunk should have the next 5 elements, and so on.

How can I do this?

Upvotes: 1

Views: 2431

Answers (3)

marsipan
marsipan

Reputation: 363

Here a one liner without iterators:

>>> list1 = [123,452,342,533,222,402,124,125,263,254,44,987,
             78,655,741,165,597,26,15,799,100,154,122,563]  
>>> list2 = [2,5,14,3]
>>> [list1[sum(list2[:i]):sum(list2[:i])+n] for i,n in enumerate(list2)]
[[123, 452], 
[342, 533, 222, 402, 124], 
[125, 263, 254, 44, 987, 78, 655, 741, 165, 597, 26, 15, 799, 100], 
[154, 122, 563]]

Upvotes: 1

Woody Pride
Woody Pride

Reputation: 13975

There are lots of ways to do this. One way is to create a list of indices for slicing, using itertools.accumulate()

from itertools import accumulate
list1 = [123,452,342,533,222,402,124,125,263,254,44,987,78,655,741,165,597,26,15,799,100,154,122,563]  
list2 = [2,5,14,3] ##these numbers specify desired chunk sizes  
ind = [0] + list(accumulate(list2))

[list1[ind[i]:ind[i+1]] for i in range(len(ind)-1)]

This gives the following result:

[[123, 452],
 [342, 533, 222, 402, 124],
 [125, 263, 254, 44, 987, 78, 655, 741, 165, 597, 26, 15, 799, 100],
 [154, 122, 563]]

Upvotes: 0

bnaecker
bnaecker

Reputation: 6470

Create an iterator over the data, and then call next on it for each range you need:

>>> data = [123,452,342,533,222,402,124,125,263,254,44,987,78,655,741,165,597,26,15,799,100,154,122,563] 
>>> sizes = [2, 5, 14, 3]
>>> it = iter(data)
>>> [[next(it) for _ in range(size)] for size in sizes]
[[123, 452],
 [342, 533, 222, 402, 124],
 [125, 263, 254, 44, 987, 78, 655, 741, 165, 597, 26, 15, 799, 100],
 [154, 122, 563]]

Upvotes: 9

Related Questions