Вы также можете решить эту проблему, используя нарезку списка, чтобы разумно разделить ваш входной список и вычислить среднее значение по разделам списка:
def moving_average(data,window):
"""The partitions begin with window-1 None. Then follow partial lists, containing
window-sized elements. We do this only up to len(data)-window+1 as the following
partitions would have less then window elements."""
parts = [None]*(window-1) + [ data[i:i+window] for i in range(len(data)-window+1)]
# The None's The sliding window of window elements
# we return None if the value is None else we calc the avg
return [ sum(x)/window if x else None for x in parts]
print( moving_average([2,3,4,5,8,5,4,3,2,1], 1) )
print( moving_average([2,3,4,5,8,5,4,3,2,1], 2) )
print( moving_average([2,3,4,5,8,5,4,3,2,1], 3) )
Вывод (parts
включен как комментарий):
# [[2], [3], [4], [5], [8], [5], [4], [3], [2], [1]]
[2.0, 3.0, 4.0, 5.0, 8.0, 5.0, 4.0, 3.0, 2.0, 1.0]
# [None, [2, 3], [3, 4], [4, 5], [5, 8], [8, 5], [5, 4], [4, 3], [3, 2], [2, 1]]
[None, 2.5, 3.5, 4.5, 6.5, 6.5, 4.5, 3.5, 2.5, 1.5]
# [None, None, [2, 3, 4], [3, 4, 5], [4, 5, 8], [5, 8, 5], [8, 5, 4],
# [5, 4, 3], [4, 3, 2], [3, 2, 1]]
[None, None, 3.0, 4.0, 5.666666666666667, 6.0, 5.666666666666667, 4.0, 3.0, 2.0]