Iteration over list slices

后端 未结 9 627
名媛妹妹
名媛妹妹 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 02:01

    Answer to the last part of the question:

    question update: How to modify the function you have provided to store the extra items and use them when the next fatherList is fed to the function?

    If you need to store state then you can use an object for that.

    class Chunker(object):
        """Split `iterable` on evenly sized chunks.
    
        Leftovers are remembered and yielded at the next call.
        """
        def __init__(self, chunksize):
            assert chunksize > 0
            self.chunksize = chunksize        
            self.chunk = []
    
        def __call__(self, iterable):
            """Yield items from `iterable` `self.chunksize` at the time."""
            assert len(self.chunk) < self.chunksize
            for item in iterable:
                self.chunk.append(item)
                if len(self.chunk) == self.chunksize:
                    # yield collected full chunk
                    yield self.chunk
                    self.chunk = [] 
    

    Example:

    chunker = Chunker(3)
    for s in "abcd", "efgh":
        for chunk in chunker(s):
            print ''.join(chunk)
    
    if chunker.chunk: # is there anything left?
        print ''.join(chunker.chunk)
    

    Output:

    abc
    def
    gh
    

提交回复
热议问题