You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Moving Average定义用Python for循环计算n周期移动平均列表ma

Python for循环实现n周期移动平均

实现说明

根据移动平均计算公式 MAn(t) = (Pt + Pt-1 + ... + Pt-(n-1)) / n,实现满足以下要求:

  • 输入参数为价格列表prices、周期整数n
  • 输出移动平均列表ma长度和prices完全一致,前n-1个值为None
  • 全程使用for循环实现逻辑

完整实现代码

def calculate_ma(prices: list, n: int) -> list:
    ma = []
    price_count = len(prices)
    # 填充前n-1个空值
    for _ in range(min(n-1, price_count)):
        ma.append(None)
    # 周期大于价格总数时直接返回
    if price_count < n:
        return ma
    # 遍历计算每个窗口的均值
    for idx in range(n-1, price_count):
        current_window = prices[idx - n + 1: idx + 1]
        window_avg = sum(current_window) / n
        ma.append(window_avg)
    return ma

调用示例

# 测试样例
price_list = [10, 12, 11, 13, 14, 16, 15]
period = 3
ma_result = calculate_ma(price_list, period)
print(ma_result)
# 输出结果:[None, None, 11.0, 12.0, 12.666666666666666, 14.333333333333334, 15.0]

原有参考代码的问题修复点

  • 补充了prices作为函数入参,支持传入任意价格序列
  • 修正了前n-1个值的填充逻辑,使用单独的None元素而非字符串
  • 将原有的while循环替换为题目要求的for循环
  • 补充了边界情况处理:当价格序列长度小于周期n时,返回全None的等长列表
  • 保证输出列表长度和输入价格列表长度完全一致

内容的提问来源于stack exchange,提问作者kris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 22:27:03