I want to divide an iterator into N equal chunks. The chunks themselves need to be iterators.
Here's some examples of what I want to achieve:
iter1 = iter(range(10))
chunks = split_n(iter1, n=2)
outputs iterator:
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]]
iter2 = iter(range(20))
chunks = split_n(iter2, n=4)
outputs iterator:
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]]
If an iterator is not evenly divisible, I want the remaining elements to be spread out so that the chunks are "as equal" as possible.
iter3 = iter(range(30))
chunks = split_n(iter3, n=4)
outputs iterator:
[[0, 1, 2, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 13, 14, 15],
[16, 17, 18, 19, 20, 21, 22],
[23, 24, 25, 26, 27, 28, 29]]
One important caveat is that at no point should an iterator be converted to a list, as the iterators can be very huge and it would simply consume too much memory.