Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a Python list logarithmically

I am trying to do the following..

I have a list of n elements. I want to split this list into 32 separate lists which contain more and more elements as we go towards the end of the original list. For example from:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

I want to get something like this:

b = [[1],[2,3],[4,5,6,7],[8,9,10,11,12]]

I've done the following for a list containing 1024 elements:

for i in range (0, 32):
    c = a[i**2:(i+1)**2]
    b.append(c)

But I am stupidly struggling to find a reliable way to do it for other numbers like 256, 512, 2048 or for another number of lists instead of 32.

like image 644
vshotarov Avatar asked Feb 22 '26 20:02

vshotarov


1 Answers

Use an iterator, a for loop with enumerate and itertools.islice:

import itertools
def logsplit(lst):
    iterator = iter(lst)
    for n, e in enumerate(iterator):
        yield itertools.chain([e], itertools.islice(iterator, n))

Works with any number of elements. Example:

for r in logsplit(range(50)):
    print(list(r))

Output:

[0]
[1, 2]
[3, 4, 5]
[6, 7, 8, 9]
... some more ...
[36, 37, 38, 39, 40, 41, 42, 43, 44]
[45, 46, 47, 48, 49]

In fact, this is very similar to this problem, except it's using enumerate to get variable chunk sizes.

like image 92
tobias_k Avatar answered Feb 24 '26 09:02

tobias_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!