Itertools Batched Lazy Chunks
Chunk any iterable lazily with itertools.batched so large datasets stream through fixed-size batches without materializing full lists.
Code
from itertools import batched, islice
def endless_ids(start: int = 0):
"""模拟无限数据源。"""
n = start
while True:
yield n
n += 1
if __name__ == '__main__':
# batched(3.12+)惰性产出定长元组,最后一批可短
source = endless_ids()
for batch in batched(islice(source, 107), 25):
print(f'batch of {len(batch)}: {batch[0]}..{batch[-1]}')
# 手写等价物(3.12 之前):zip 严格模式 + 迭代器切片
def batched_manual(iterable, n):
it = iter(iterable)
while True:
chunk = tuple(islice(it, n))
if not chunk:
return
yield chunk
manual = list(batched_manual(range(7), 3))
print(manual)Inside the snippet
Itertools Batched Lazy Chunks comes down to the functions endless_ids and batched_manual.
Repetition is confined to while True — the rest of the file is straight-line.
Using it
The main signature reads def endless_ids(start: int = 0)
Running the file prints labeled results such as batch of — each operation’s effect is visible in the output.
Key statements
def endless_ids(start: int = 0):
"""模拟无限数据源。"""
n = start
while True:
yield n
n += 1
def batched_manual(iterable, n):
it = iter(iterable)
while True:
chunk = tuple(islice(it, n))
if not chunk:
return
yield chunk
Interactive Tools for This Topic
FAQ
- What does Itertools Batched Lazy Chunks print when run?
- Invoke the file as-is — the `batch of` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.