Iterate over a python sequence in multiples of n?

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

    you can create the following generator

    def chunks(seq, size):
        a = range(0, len(seq), size)
        b = range(size, len(seq) + 1, size)
        for i, j in zip(a, b):
            yield seq[i:j]
    

    and use it like this:

    for i in chunks('abcdef', 2):
        print(i)
    

提交回复
热议问题