def moving_average ( iterable , n ) : it = iter ( iterable ) d = collections . deque ( itertools . islice ( it , n - 1 ) ) d . appendleft ( 0 ) s = sum ( d ) for elem in it : s += elem - d . popleft ( ) d . append ( elem ) yield s / float ( n )
python moving average nested loop
From Python collections module documentation
def moving_average(iterable, n):
    """
    From Python collections module documentation

    moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
    """
    it = iter(iterable)
    d = collections.deque(itertools.islice(it, n - 1))
    d.appendleft(0)
    s = sum(d)
    for elem in it:
        s += elem - d.popleft()
        d.append(elem)
        yield s / float(n)