-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathiter.py
37 lines (28 loc) · 752 Bytes
/
iter.py
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
30
31
32
33
34
35
36
37
from __future__ import annotations
import itertools
from collections.abc import Generator
from collections.abc import Iterable
from typing import TypeVar
T = TypeVar('T')
def chunk_iter(
iterable: Iterable[T],
n: int,
) -> Generator[tuple[T, ...]]:
"""Yields an iterator in chunks
For example you can do
for a, b in chunk_iter([1, 2, 3, 4, 5, 6], 2):
print('{} {}'.format(a, b))
# Prints
# 1 2
# 3 4
# 5 6
Args:
iterable - Some iterable
n - Chunk size (must be greater than 0)
"""
assert n > 0
iterable = iter(iterable)
chunk = tuple(itertools.islice(iterable, n))
while chunk:
yield chunk
chunk = tuple(itertools.islice(iterable, n))