How to write a pager for Python iterators?

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

    def group_by(iterable, size):
        """Group an iterable into lists that don't exceed the size given.
    
        >>> group_by([1,2,3,4,5], 2)
        [[1, 2], [3, 4], [5]]
    
        """
        sublist = []
    
        for index, item in enumerate(iterable):
            if index > 0 and index % size == 0:
                yield sublist
                sublist = []
    
            sublist.append(item)
    
        if sublist:
            yield sublist
    

提交回复
热议问题