用C或Python移动3个元素的平均值 [英] moving average of 3 elements by C or Python
问题描述
我想计算3个元素的移动平均值.
I want to calculate the moving average of 3 elements.
例如,我有25个销售数据元素.我需要通过对这25个数据元素取平均值来计算移动平均值.
For example, I have a 25 elements of sales data. I need to calculate the moving average taken from averaging these 25 elements of data.
当将实际数组作为数据给出时,我想编写一个程序,该程序将确定3个元素的移动平均值并创建一个数组.数组中的元素数比给定序列短2个元素. 例如,如果给我:
When a real array is given as data, I want to write a program that will determines a 3 element moving average and creates an array. The number of elements in the array becomes 2 elements shorter than the given sequence. For example, if I am given:
[7.0, 9.0, 5.0, 1.0, 3.0]
我想得到:
[7.0, 5.0, 3.0]
推荐答案
You could use a Python deque
for doing this as follows:
from collections import deque
prices = [7.0, 9.0, 5.0, 1.0, 3.0]
moving_average = deque()
total = 0.0
days = 3
averages = []
for price in prices:
moving_average.append(price)
total += price
if len(moving_average) > days: # Length of moving average
total -= moving_average.popleft()
averages.append(total / float(len(moving_average)))
print averages
这将显示以下输出:
[7.0, 8.0, 7.0, 5.0, 3.0]
或者您可以如下跳过初始输入:
Or you could skip the initial entries as follows:
print averages[days-1:]
给予:
[7.0, 5.0, 3.0]
这篇关于用C或Python移动3个元素的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!