Last active
March 21, 2022 14:37
-
-
Save iKlotho/1329b409fcb401391285ee6202a41b87 to your computer and use it in GitHub Desktop.
split given list to chunks most equally
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def chunk_generator(chunks): | |
for chunk in chunks: | |
yield chunk | |
def split_to_chunks(paginate_list, chunk_size): | |
""" | |
It converts given list to mostly | |
equal sized arrays | |
""" | |
chunkcount = len(paginate_list) // chunk_size | |
chunk_list = [] | |
remaining = [] | |
for i in range(chunk_size): | |
lower, upper = i, i + 1 | |
if lower == chunk_size - 1: | |
upper = len(paginate_list) | |
chunk = paginate_list[chunkcount * lower: chunkcount * upper] | |
if len(chunk) > chunkcount: | |
remaining.extend(chunk[chunkcount:]) | |
chunk = chunk[:chunkcount] | |
chunk_list.append(chunk) | |
if remaining: | |
chunk = chunk_generator(chunk_list) | |
while remaining: | |
next(chunk).append(remaining.pop()) | |
return chunk_list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment