Saturday, 17 February 2024

Python: Batch an Interator

from itertools import islice

def batched(iterator, batch_size):
    """
    Takes an iterator and a batch-size, and returns an iterator that yields batches of the given size.
    
    Parameters:
    - iterator: An iterator from which to generate batches.
    - batch_size: An integer specifying the size of each batch.
    
    Yields:
    - Batches of elements from the input iterator, each batch being a list of elements up to the specified batch_size.
    """
    iterator = iter(iterator)  # Ensure it's an iterator
    while True:
        batch = list(islice(iterator, batch_size))
        if not batch:
            break
        yield batch

Usage:

for batch in batched(range(80), 9):
    print(batch)


d = {str(idx): idx for idx in range(10)}

for batch in batched(d.items(), 3):
    for key, value in batch:
        print(key, value)

Output

[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, 30, 31, 32, 33, 34, 35]
[36, 37, 38, 39, 40, 41, 42, 43, 44]
[45, 46, 47, 48, 49, 50, 51, 52, 53]
[54, 55, 56, 57, 58, 59, 60, 61, 62]
[63, 64, 65, 66, 67, 68, 69, 70, 71]
[72, 73, 74, 75, 76, 77, 78, 79]
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9

No comments:

Post a Comment

Parse Wikipedia dump

""" This module processes Wikipedia dump files by extracting individual articles and parsing them into a structured format, ...