Iterate over a ‘window’ of adjacent elements in Python

前端 未结 5 1610
情话喂你
情话喂你 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:18

    This page shows how to implement a sliding window with itertools. http://docs.python.org/release/2.3.5/lib/itertools-example.html

    def window(seq, n=2):
        "Returns a sliding window (of width n) over data from the iterable"
        "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
        it = iter(seq)
        result = tuple(islice(it, n))
        if len(result) == n:
            yield result    
        for elem in it:
            result = result[1:] + (elem,)
            yield result
    

    Example output:

    >>> list(window(range(10)))
    [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
    

    You'd need to change it to fill left and right if you need.

提交回复
热议问题