Iterate over a python sequence in multiples of n?

后端 未结 17 721
北荒
北荒 2020-12-01 17:45

How do I process the elements of a sequence in batches, idiomatically?

For example, with the sequence \"abcdef\" and a batch size of 2, I would like to do something

17条回答
  •  渐次进展
    2020-12-01 18:30

    The itertools doc has a recipe for this:

    from itertools import izip_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 izip_longest(fillvalue=fillvalue, *args)
    

    Usage:

    >>> l = [1,2,3,4,5,6,7,8,9]
    >>> [z for z in grouper(l, 3)]
    [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
    

提交回复
热议问题