好的,我正在写一个类,它将计算价格列表上的简单移动平均值。它计算每N个数字的平均价格,不计算前N-1天。这就是我所拥有的:
class Simplemovingaverage():
def __init__(self, Nday, list_of_prices):
self._Nday = Nday
self._list_of_prices = list_of_prices
def calculate(self):
for i in range(len(self._list_of_prices)):
if i < self._Nday:
average = 0
elif i == self._Nday:
average = sum(self._list_of_prices[:self._Nday])/self._Nday
else:
average = sum(self._list_of_prices[i-self._Nday:i])/self._Nday
print(average)
我在shell 'x = Simplemovingaverage(3, [1,2,3,4,5,6,7,8,9,10])'
上创建一个class对象,然后通过“x.calculate”执行calculate方法,得到的输出是:
所以从我的数字列表来看,它只能计算到7,8,9,9,最后一个数字应该是9,因为这是8,9,10的平均值,而且因为N是3,所以应该只有3个0。这是我要查找的输出:
0
0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0
好的,这里是清理:
首先,您需要在任何地方使用},而不是{}(也可以使用
i+1
,因为range
给出的是{range(1, n+1)
)。在其次,您不需要使用特殊情况}相同)。在
i+1==self.navg
(:m
与{第三,返回一个列表比打印结果更有意义(尽管我喜欢另一个应答者使用
yield
使其成为生成器的想法!)在第四,没有真正的理由隐藏数字和列表,所以我删除了下划线(python不是java或c++!)。在
最后,这比某个“天数”内平均的“价格列表”更一般,因此为了更一般性,我重新命名了参数。在
当运行为
^{pr2}$退货
(以N-1开头的0,意味着输出列表与输入列表具有相同的基数,我认为这正是您真正想要的)。在
相关问题 更多 >
编程相关推荐