Iterate over a python sequence in multiples of n?

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

    From the docs of more_itertools: more_itertools.chunked()

    more_itertools.chunked(iterable, n)
    

    Break an iterable into lists of a given length:

    >>> list(chunked([1, 2, 3, 4, 5, 6, 7], 3))
    [[1, 2, 3], [4, 5, 6], [7]]
    

    If the length of iterable is not evenly divisible by n, the last returned list will be shorter.

提交回复
热议问题