Iteration over list slices

后端 未结 9 630
名媛妹妹
名媛妹妹 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:57

    If you want to be able to consume any iterable you can use these functions:

    from itertools import chain, islice
    
    def ichunked(seq, chunksize):
        """Yields items from an iterator in iterable chunks."""
        it = iter(seq)
        while True:
            yield chain([it.next()], islice(it, chunksize-1))
    
    def chunked(seq, chunksize):
        """Yields items from an iterator in list chunks."""
        for chunk in ichunked(seq, chunksize):
            yield list(chunk)
    

提交回复
热议问题