Rea Kalampaliki
Rea Kalampaliki

Reputation: 164

Split a nested list in equally sized parts

I would like to separate a list of 80 sets of coordinates in backets of 8 sets each.

This is what I tried. I found the indexes where the backets start. I sliced the list of coordinates between one index and the next. FInally, I used an if statement to create the final backet, since there is no 'next' index for the last index. Any ideas to improve this approach? Thank you.

nested_lst = [[0.5, 11.3, 5.1]]*80
indexes = list(range(len(nested_lst)))[::8]
backets = []
for i in range(len(indexes)):
    if i != len(indexes) - 1:
        backet = nested_lst[indexes[i]:indexes[i+1]]
    else:
        backet = nested_lst[indexes[i]:]
    backets.append(backet)

Upvotes: 0

Views: 131

Answers (3)

ALai
ALai

Reputation: 799

Could this work for you? Reference answer here

def batch(iterable, n=1):
    l = len(iterable)
    for ndx in range(0, l, n):
        yield iterable[ndx:min(ndx + n, l)]

nested_lst = [[0.5, 11.3, 5.1]]*80
backets = list(batch(nested_lst, n=8))

print(backets)

The results are matching yours, but this might be a more efficient and better-looking way to do it

Upvotes: 1

simre
simre

Reputation: 668

Use numpy! It'll be much faster and simpler

import numpy as np

coordinates = np.array([0.5, 11.3, 5.1]*80)

# Number of buckets
chunks = 8

# It is a must to have equally sized buckets, but reshape will also fail is this is not ok...
assert(coordinates.size % chunks == 0)

# Size of each bucket
chunksize = coordinates.size // chunks

# There you go, 8 buckets with the same size
res = coordinates.reshape((chunks, chunksize))

Upvotes: 0

Shreya Shukla
Shreya Shukla

Reputation: 11

The coordinates list can be flattened, and a simple iteration should work.

coordinates = [i for i in coordinates]
backets = []

i = 0
while(i < len(coordinates)):
    l = []
    for _ in range(8):
        l.append(coordinates[i])
        i += 1
    backets.append(l)

Upvotes: 1

Related Questions