我有一个 float 列表,我想从我的第一个列表生成另一个周期返回列表。
这是工厂实现的运行(未经测试 - 显然没有错误检查/处理):
a = [100,105,100,95,100]
def calc_period_returns(values, period):
output = []
startpos, endpos = (period, len(values)-1)
while True:
current = values[startpos]
previous = values[startpos-period]
ret = 100*((current-previous)/(1.0*previous))
output.append(ret)
startpos += period
if startpos > endpos:
break
return output
calc_period_returns(a,1)
# Expected output:
# [5.0, -4.7619047619047619, -5.0, 5.2631578947368416]
是否有更 pythonic 的方式来执行此操作 - 也许使用列表理解和映射?
最佳答案
我不知道你的数字列表有多大,但如果你要处理大量数字,你应该看看 numpy。副作用是计算看起来简单多了。
使用 numpy,您可以为数据创建一个数组
>>> import numpy as np
>>> a = np.array([100,105,100,95,100], dtype=float)
像处理简单的数字一样处理数组
>>> np.diff(a) / a[:-1] * 100.
[ 5. -4.76190476 -5. 5.26315789]
关于python - 什么是计算数字列表百分比变化的最pythonic方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10226551/