我有一个类似于累积求和的函数,我只想加权。因此,使用外部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)))
但这是一个缓慢的版本,如果你有大的奖励数组。是否有任何现有功能可以更快地完成此任务?在
注意:我正在使用
Python 3.6.0
您可以尝试使用
itertools
:https://docs.python.org/3/library/itertools.htmlitertools.accumulate
函数可能比np.cumsum
:https://stackoverflow.com/a/39534850/7175945快如果你真的不想使用
numpy
,我想这应该是你要找的,否则你已经写的也是一个可行的选择。在相关问题 更多 >
编程相关推荐