Iterate over a python sequence in multiples of n?

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

    How about itertools?

    from itertools import islice, groupby
    
    def chunks_islice(seq, size):
        while True:
            aux = list(islice(seq, 0, size))
            if not aux: break
            yield "".join(aux)
    
    def chunks_groupby(seq, size):
        for k, chunk in groupby(enumerate(seq), lambda x: x[0] / size):
            yield "".join([i[1] for i in chunk])
    

提交回复
热议问题