How to write a pager for Python iterators?

前端 未结 6 1273
执念已碎
执念已碎 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:49

    Why aren't you using this?

    def grouper( page_size, iterable ):
        page= []
        for item in iterable:
            page.append( item )
            if len(page) == page_size:
                yield page
                page= []
        yield page
    

    "Each page would itself be an iterator with up to page_size" items. Each page is a simple list of items, which is iterable. You could use yield iter(page) to yield the iterator instead of the object, but I don't see how that improves anything.

    It throws a standard StopIteration at the end.

    What more would you want?

提交回复
热议问题