gpt4 book ai didi

python - 如何同时修改两个相互关联的列表?

转载 作者:行者123 更新时间:2023-12-01 06:20:54 26 4
gpt4 key购买 nike

我有两个空白列表:intitialListfinalList和一个应该进入 initialList 的初始值和样本列表 sampleList = [12,3,1,4,25,3,2,22,12,32,34,2,1,5,7] 。现在我想做的是编写一个程序,首先在 initialList 中插入初始值然后进行一些计算并将值插入 finalList然后 finalList 的第一个值成为 initialList 的第二个值并再次进行一些计算等等。这是一种曲折的东西。值以锯齿形方式填充。我的做法:

intialList = []
finalList = []
intialValue = 30
eff = 0.25
sampleList = [12,3,1,4,25,3,2,22,12,32,34,2,1,5,7]
for a in sampleList:
if a < 10:
intialList.append(intialValue)
finalList.append(intialValue + intialValue*eff)
else:
intialList.append(intialValue)
finalList.append(intialValue - intialValue*eff)
print("initial list:", intialList)
print("final list:", finalList)

我真的不知道如何解决这个问题。期望的输出:

initial list: [30, 22.5, 28.125, 35.156, 43.954, 32.96, 24.72]
finalist list: [22.5, 28.125, 35.156, 43.945, 32.96, 24.72]

结果存储在finalList中首先是 initial value存储在 initialList 的索引 0 处之后的最终结果来自finalList存储在initialList中。

最佳答案

根据您想要的输出,您希望在 sampleList 迭代期间更改 intalValue:

finalList = []
intialValue = 30
intialList = [intialValue]

eff = 0.25
sampleList = [12,3,1,4,25,3,2,22,12,32,34,2,1,5,7]


for a in sampleList:
if a < 10:
calculated_value = intialValue + intialValue * eff

else:
calculated_value = intialValue - intialValue * eff

intialValue = calculated_value
finalList.append(intialValue)
intialList.append(intialValue)

print(intialList)
print(finalList)

输出:

[30, 22.5, 28.125, 35.15625, 43.9453125, 32.958984375, 41.19873046875, 51.4984130859375, 38.623809814453125, 28.967857360839844, 21.725893020629883, 16.294419765472412, 20.368024706840515, 25.460030883550644, 31.825038604438305, 39.78129825554788]
[22.5, 28.125, 35.15625, 43.9453125, 32.958984375, 41.19873046875, 51.4984130859375, 38.623809814453125, 28.967857360839844, 21.725893020629883, 16.294419765472412, 20.368024706840515, 25.460030883550644, 31.825038604438305, 39.78129825554788]

关于python - 如何同时修改两个相互关联的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60361413/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com