Skip to content

Instantly share code, notes, and snippets.

@fopina
Created October 22, 2021 23:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fopina/dc3ccd38e6bab03e10ab4d8d05b7f8b0 to your computer and use it in GitHub Desktop.
Save fopina/dc3ccd38e6bab03e10ab4d8d05b7f8b0 to your computer and use it in GitHub Desktop.
python: split list into fixed number of evenly distributed sublists
"""
Googling a solution for this seems to always end with [numpy array_split](https://numpy.org/doc/stable/reference/generated/numpy.array_split.html)
This avoids having numpy as dependency just for this
"""
def array_split(array, parts):
"""
split an array into parts arrays, evenly size
>>> list(array_split(list(range(12)), 10))
[[0, 1], [2, 3], [4], [5], [6], [7], [8], [9], [10], [11]]
>>> list(array_split(list(range(8)), 10))
[[0], [1], [2], [3], [4], [5], [6], [7]]
>>> list(array_split(list(range(10)), 10))
[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
>>> list(array_split([], 10))
[]
"""
n = len(array)
np, nl = divmod(n, parts)
i = 0
for p in range(parts if np > 0 else nl):
s = np + 1 if p < nl else np
yield array[i:i+s]
i += s
if __name__ == "__main__":
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment