Iterable is divided into N pieces and returned as a generator.
I improved it by referring to the link provided in the comment. It's shortened to 3 lines and can handle an infinite list. Split iterator into chunks with python
python
import itertools
def splitparN(iterable, N=3):
for i, item in itertools.groupby(enumerate(iterable), lambda x: x[0] // N):
yield (x[1] for x in item)
for x in splitparN(range(12)):
print(tuple(x))
"""
output:
(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
(9, 10, 11)
"""
eternal = libs.splitparN(itertools.cycle("hoge"))
print([tuple(next(eternal)) for x in range(4)])
#output:[('h', 'o', 'g'), ('e', 'h', 'o'), ('g', 'e', 'h'), ('o', 'g', 'e')]
#itertools.Can be undone with chain
print(tuple(itertools.chain.from_iterable(splitparN(range(12)))))
#output:(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
Recommended Posts