IndexError:列表赋值索引超出python 2.7.11中的范围

时间:2016-04-08 15:31:00

标签: arrays python-2.7 python-3.x numpy matplotlib

我只是使用python解决问题,我的代码是:

from math import sin,pi
import numpy
import numpy as np
import pylab
N=20
x = np.linspace(0,1, N)
def v(x):
    return 100*sin(pi*x)

#set up initial condition
u0 = [0.0]              # Boundary conditions at t= 0
for i in range(1,N):
    u0[i] = v(x[i])

我想通过更新range(0, N)之后的v(x)来绘制结果。它看起来很简单,但也许你们可以提供帮助,因为它给了我一个错误,比如

Traceback (most recent call last):
  File "/home/universe/Desktop/Python/sample.py", line 13, in <module>
    u0[i] = v(x[i])
IndexError: list assignment index out of range

3 个答案:

答案 0 :(得分:1)

您可以将u0[i] = v(x[i])更改为u0.append(v(x[i]))。但你应该写得更优雅

u0 = [v(xi) for xi in x]

指数i是错误磁铁。

答案 1 :(得分:1)

由于您使用numpy,我建议使用np.vectorize。这样你就可以将数组x直接传递给函数,函数将返回一个相同大小的数组,并在输入数组的每个元素上应用函数。

from math import sin,pi
import numpy
import numpy as np
import pylab
N=20
x = np.linspace(0,1, N)
def v(x):
    return 100*sin(pi*x)

vectorized_v = np.vectorize(v) #so that the function takes an array of x's and returns an array again
u0 = vectorized_v(x) 

输出:

array([  0.00000000e+00,   1.64594590e+01,   3.24699469e+01,
         4.75947393e+01,   6.14212713e+01,   7.35723911e+01,
         8.37166478e+01,   9.15773327e+01,   9.69400266e+01,
         9.96584493e+01,   9.96584493e+01,   9.69400266e+01,
         9.15773327e+01,   8.37166478e+01,   7.35723911e+01,
         6.14212713e+01,   4.75947393e+01,   3.24699469e+01,
         1.64594590e+01,   1.22464680e-14])

答案 2 :(得分:0)

u是一个包含一个元素的列表,因此您无法为不存在的索引分配值。而是使u成为字典

u = {}
u[0] = 0.0
for i in range(1,N):
    u[i] = v(x[i])