python计算滑动平均的代码
时间: 2023-12-20 08:57:52 浏览: 145
滑动平均算法
4星 · 用户满意度95%
以下是一个简单的 Python 代码,用于计算滑动平均:
```python
def moving_average(data, window_size):
# 确保窗口大小不超过数据长度
window_size = min(window_size, len(data))
# 初始化滑动平均值列表
moving_averages = []
# 遍历数据
for i in range(len(data)):
if i < window_size:
# 如果数据不足以填满窗口,直接取平均值
moving_averages.append(sum(data[:i+1]) / len(data[:i+1]))
else:
# 计算滑动平均值
moving_averages.append(sum(data[i-window_size+1:i+1]) / window_size)
return moving_averages
```
使用方法:
```python
data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
window_size = 3
moving_averages = moving_average(data, window_size)
print(moving_averages)
```
输出结果:
```
[1.0, 1.5, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]
```
阅读全文