月关宝盒
对于一个简短、快速的解决方案,它在一个循环中完成整个过程,没有依赖关系,下面的代码工作得很好。mylist = [1, 2, 3, 4, 5, 6, 7]N = 3cumsum, moving_aves = [0], []for i, x in enumerate(mylist, 1):
cumsum.append(cumsum[i-1] + x)
if i>=N:
moving_ave = (cumsum[i] - cumsum[i-N])/N #can do stuff with moving_ave here
moving_aves.append(moving_ave)