Iterate over a python sequence in multiples of n?

后端 未结 17 772
北荒
北荒 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:29

    Here is a solution, which yields a series of iterators, each of which iterates over n items.

    def groupiter(thing, n):
        def countiter(nextthing, thingiter, n):
            yield nextthing
            for _ in range(n - 1):
                try:
                    nextitem = next(thingiter)
                except StopIteration:
                    return
                yield nextitem
        thingiter = iter(thing)
        while True:
            try:
                nextthing = next(thingiter)
            except StopIteration:
                return
            yield countiter(nextthing, thingiter, n)
    

    I use it as follows:

    table = list(range(250))
    for group in groupiter(table, 16):
        print(' '.join('0x{:02X},'.format(x) for x in group))
    

    Note that it can handle the length of the object not being a multiple of n.

提交回复
热议问题