英文:
Appending issue in a list in Python
问题
我有一个名为Ci
的列表。我在循环中执行一个操作并附加数值。但我无法获得预期的输出。我该如何修复它?
arCi=[]
Ci=[1.0]
for i in range(0,4):
Ci=Ci[0]*i
arCi.append(Ci)
Ci=list(arCi)
print(Ci)
当前的输出是
[0.0, 0.0, 0.0, 0.0]
预期的输出是
[0.0, 1.0, 2.0, 3.0]
英文:
I have a list Ci
. I am performing an operation within a loop and appending the values. But I am not able to obtain the expected output. How do I fix it?
arCi=[]
Ci=[1.0]
for i in range(0,4):
Ci=Ci[0]*i
arCi.append(Ci)
Ci=list(arCi)
print(Ci)
The current output is
[0.0, 0.0, 0.0, 0.0]
The expected output is
[0.0, 1.0, 2.0, 3.0]
答案1
得分: -1
在第一次迭代中,当 i=0
时,你将 Ci
的第一项设为 0.0
,然后你迭代使用 0.0
,从而得出答案为 0.0
。
Ci = []
num = 1.0
for i in range(0, 4):
Ci.append(num * i)
print(Ci) # 输出正确结果
英文:
In the first iteration, when i=0
, you make the first term of Ci
as 0.0
and then you are using 0.0
iteratively which gives the answer as 0.0
.
Ci = []
num = 1.0
for i in range(0,4):
Ci.append(num*i)
print(Ci) #yields correct result
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论