Last active
July 4, 2020 08:23
-
-
Save duchenpaul/fb37659f9dc1fd5d9e5f4cb6f530c8fe to your computer and use it in GitHub Desktop.
Split list into pieces evenly
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 chunks(l, n): | |
n = max(1, n) | |
result = [l[i:i+n] for i in range(0, len(l), n)] | |
if len(result) * n > len(l): | |
last = result.pop(-1) | |
result[-1] += last | |
return result | |
lenf = 205 | |
div = 4 | |
print(list(chunks(range(lenf), lenf//div))) | |
''' | |
[range(0, 51), range(51, 102), range(102, 153), range(153, 205)] | |
''' | |
def chunks(l, n): | |
"""Yield n number of sequential chunks from l.""" | |
d, r = divmod(len(l), n) | |
for i in range(n): | |
si = (d+1)*(i if i < r else r) + d*(0 if i < r else i - r) | |
yield l[si:si+(d+1 if i < r else d)] | |
''' | |
Which for l = range(16) and n = 6 produces: | |
[0, 1, 2] | |
[3, 4, 5] | |
[6, 7, 8] | |
[9, 10, 11] | |
[12, 13] | |
[14, 15] | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment