How to write a pager for Python iterators?

前端 未结 6 1236
执念已碎
执念已碎 2021-01-05 00:11

I\'m looking for a way to \"page through\" a Python iterator. That is, I would like to wrap a given iterator iter and page_size with another iterator that wou

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-05 00:40

    Look at grouper(), from the itertools recipes.

    from itertools import zip_longest
    
    def grouper(iterable, n, fillvalue=None):
        "Collect data into fixed-length chunks or blocks"
        # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
        args = [iter(iterable)] * n
        return zip_longest(*args, fillvalue=fillvalue)
    

提交回复
热议问题