使用函数修改列表中的每个元素,然后修改列表中所有元素



我有一个利率列表,如下所示:

rates = [
-0.0005710,
-0.001913,
]

我有一个函数,它将这个列表作为输入,并计算不同的风险指标。但是,我想首先通过返回原始列表来使用此列表建立基线。接下来,我想为列表中的每个元素添加0.001,然后返回列表。最后,我想将0.001添加到列表中的所有元素中。我会拿下价格列表,然后返回以下列表:

rates_adjusted = [
-0.0005710,
-0.001913,
]
rates_adjusted = [
0.000429,
-0.001913,
]
rates_adjusted = [
-0.0005710,
-0.000913,
]
rates_adjusted = [
0.000429,
-0.000913,
]

首先,我返回正常列表,然后为列表中的每个元素返回一个新列表,但将0.001添加到其中一个元素中。有没有一种方法可以同时在for循环中做到这一点?我曾尝试过使用enumerate对for循环进行元素操作,但后来我错过了基线和同时更改所有元素的部分。

它可以用几种方法来完成——这里是其中之一,我将在进行过程中进行解释:

rates = [-0.0005710, -0.001913,0.01034] # I modified your list by adding one element just to demonstrate
adjs = {} # create a dictionary to house the resulting lists
adjs['rates_unadjusted']=rates #first entry in the dictionary - the original list
for i in range(len(rates)):
tmp_rates = rates.copy() #make a copy of the original list so the next iteration isn't affected
tmp_rates[i] = tmp_rates[i] +0.001 #adjust the current list element
adjs[f'rates_adjusted_{i+1}']  = tmp_rates # append the resulting list to the dictionary with a name reflecting its position
final = rates.copy() #now adjust all entries at once and append to the dictionary
for rate in rates:
final[rates.index(rate)] = rate+0.001
adjs['final_rates']  = final
adjs

输出:

{'rates_unadjusted': [-0.000571, -0.001913, 0.01034],
'rates_adjusted_1': [0.000429, -0.001913, 0.01034],
'rates_adjusted_2': [-0.000571, -0.000913, 0.01034],
'rates_adjusted_3': [-0.000571, -0.001913, 0.01134],
'final_rates': [0.000429, -0.000913, 0.01134]}

显然,您可以修改输出以满足您的需求。

最新更新