加权累计和python

2024-09-25 04:33:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似于累积求和的函数,我只想加权。因此,使用外部for循环将如下所示:

discount_rate = 0.95 
rewards = [0, 0, 10] # want to translate to: [9, 9.5, 10] (approximation)

reversed_rewards = [10, 0, 0]
new_rewards = [0] * len( rewards)

previus = 0
for index in range( len( rewards)):
     new_rewards[ index] = reversed_rewards[ index] + previus * discount_rate
     previus = new_rewards[ index]

print( list( reversed( new_rewards)))

但这是一个缓慢的版本,如果你有大的奖励数组。是否有任何现有功能可以更快地完成此任务?在


Tags: to函数innewforindexlenrate
1条回答
网友
1楼 · 发布于 2024-09-25 04:33:41

注意:我正在使用Python 3.6.0

您可以尝试使用itertools:https://docs.python.org/3/library/itertools.html

itertools.accumulate函数可能比np.cumsum:https://stackoverflow.com/a/39534850/7175945

from itertools import accumulate

def weighted():
    discount_rate = 0.95 #your discount rate
    rewards = [0, 0, 10] # want to translate to: [9, 9.5, 10](approximation)
    reversed_rewards = rewards[::-1] #list reversal
    acc = list(accumulate(reversed_rewards, lambda x,y: x*discount_rate + y))
    return acc[::-1] 

print(weighted())

如果你真的不想使用numpy,我想这应该是你要找的,否则你已经写的也是一个可行的选择。在

相关问题 更多 >