简体   繁体   English

python中的移动平均线

[英]moving average in python

I've tried to create a generator function which can find simple moving average of the list, but it doesn't work at all.我试图创建一个生成器函数,它可以找到列表的简单移动平均值,但它根本不起作用。 I think the root of the problem might be in finding sum我认为问题的根源可能在于求和

def gen(lst, n):
    s = 0
    for i, _ in enumerate(lst):
        if lst[i] < n:
            s += lst[n - (n-i)]

my code does nothing when i play it.我的代码在播放时什么都不做。 What should I do?我应该怎么办?

if lst[i] < n:

You do not define i你没有定义i

but I guess i is a index of lst so try:但我想ilst的索引,所以试试:

for i, _ in enumerate(lst):
  if lst[i] < n:
    s += lst[n - (n-i)]

EDIT:编辑:

def gen(lst, n):
    if n > len(lst):
        print("Sorry can't do this")
    try:
        for i, _ in enumerate(lst[:-(n-1)]):
            s = sum(lst[i:i+n])
            yield s/n
    except ZeroDivisionError:
        print("Sorry can't do this")

You may have some issues with this code snippet because you did not include some relevant variables and how they are used.您可能对此代码片段有一些问题,因为您没有包含一些相关变量以及它们的使用方式。

Below is an example of how you can calculate a moving average of list_of_numbers , given a position p with a period of n .下面是一个示例,说明如何计算list_of_numbers的移动平均值,给定一个位置p ,周期为n

def mAverage(list_of_numbers, p, n):
    if n < p:
        return sum(list_of_numbers[p-n:p])/n
    else:
        return sum(list_of_numbers[0:p])/(p + 1)

Note: At the beginning of the list this function will only calculate the moving average with a period equal to the position in the list.注意:在列表的开头,此函数将仅计算周期等于列表中位置的移动平均线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM