在Python中的列表中追加问题。

huangapple go评论52阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月27日 18:54:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75579531.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定