Skip to content

Instantly share code, notes, and snippets.

@fopina
Created October 22, 2021 23:55

Revisions

  1. fopina created this gist Oct 22, 2021.
    29 changes: 29 additions & 0 deletions array_split.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    """
    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()