简体   繁体   English

索引超出范围Python数值迭代

[英]Index out of range Python NUmerical Iteration

I am a beginner in Python . 我是Python的初学者。 While running the following code. 在运行以下代码时。

from array import *  
x=[]  
x[0]=.232  
for i in range(25):   
x[i+1]=1/[i+1]-5*x[i] 
end

I get an error: 我收到一个错误:

x[0]=.232 IndexError: list assignment index out of range x [0] =。232 IndexError:列表分配索引超出范围

Can someone help me sort this out 有人可以帮我解决这个问题吗

Your code has more errors, but in this particular case you are trying to access the first position ( x[0] ) of an empty array ( declared as x=[] ) 您的代码有更多错误,但是在这种特殊情况下,您尝试访问空数组( 声明为x=[] )的第一个位置( x[0] x=[]

The same error appears in the loop ( x[i+1] is index out of range since the array is empty ) and you have a syntax error, end is not a python keyword. 循环中会出现相同的错误( 由于数组为空 ,因此x[i+1]的索引超出范围 ),并且您遇到语法错误, end不是python关键字。 Finally, the body of the loop should be indented. 最后,循环的主体应缩进。

x=[] makes an empty list so you can't call x[0], so make a list of 26 elements(you need all total 26 elements) all equal to zero for convenience, x = []会创建一个空列表,因此您无法调用x [0],因此为了方便起见,将一个包含26个元素(总共需要26个元素)的列表全部设为零,

 x=[0.0]*26

or 要么

x=[0.0 for i in range(26)]

again [i+1] denotes a list and you cant do calculation with that make (i+1). 再次[i+1]表示一个列表,您无法使用该make(i + 1)进行计算。 also 1/(i+1) gives integer division make 1.0/(i+1) end is not a valid python function here, dont use it indente the next line under the for loop. 1/(i+1)给出整数除法make 1.0 /(i + 1) end在这里不是有效的python函数,请不要使用它缩进for循环下的下一行。 final programme, 最终方案

x=[0.0]*26  
x[0]=.232  
for i in range(25):   
    x[i+1]=1.0/(i+1)-5*x[i]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM