Iterate over a ‘window’ of adjacent elements in Python

前端 未结 5 1611
情话喂你
情话喂你 2020-12-15 08:33

This is more a question of elegance and performance rather than “how to do at all”, so I\'ll just show the code:

def iterate_adjacencies(gen, fill=0, size=2,         


        
5条回答
  •  醉酒成梦
    2020-12-15 09:21

    This is my version that fills, keeping the signature the same. I have previously seen the itertools recipe, but did not look at it before writing this.

    from itertools import chain
    from collections import deque
    
    def ia(gen, fill=0, size=2, fill_left=True, fill_right=False):
        gen, ssize = iter(gen), size - 1
        deq = deque(chain([fill] * ssize * fill_left,
                          (next(gen) for _ in xrange((not fill_left) * ssize))),
                    maxlen = size)
        for item in chain(gen, [fill] * ssize * fill_right):
            deq.append(item)
            yield deq
    

    Edit: I also didn't see your comments on your question before posting this.

    Edit 2: Fixed. I had tried to do it with one chain but this design needs two.

    Edit 3: As @senderle noted, only use it this as a generator, don't wrap it with list or accumulate the output, as it yields the same mutable item repeatedly.

提交回复
热议问题