How to write a pager for Python iterators?

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

    Based on the pointer to the itertools recipe for grouper(), I came up with the following adaption of grouper() to mimic Pager. I wanted to filter out any None results and wanted to return an iterator rather than a tuple (though I suspect that there might be little advantage in doing this conversion)

    # based on http://docs.python.org/library/itertools.html#recipes
    def grouper2(n, iterable, fillvalue=None):
        args = [iter(iterable)] * n
        for item in izip_longest(fillvalue=fillvalue, *args):
            yield iter(filter(None,item))
    

    I'd welcome feedback on how what I can do to improve this code.

提交回复
热议问题