Iteration over list slices

后端 未结 9 623
名媛妹妹
名媛妹妹 2020-11-30 00:59

I want an algorithm to iterate over list slices. Slices size is set outside the function and can differ.

In my mind it is something like:

for list_of_x         


        
9条回答
  •  独厮守ぢ
    2020-11-30 01:44

    Expanding on the answer of @Ants Aasma: In Python 3.7 the handling of the StopIteration exception changed (according to PEP-479). A compatible version would be:

    from itertools import chain, islice
    
    def ichunked(seq, chunksize):
        it = iter(seq)
        while True:
            try:
                yield chain([next(it)], islice(it, chunksize - 1))
            except StopIteration:
                return
    

提交回复
热议问题