我总是让错误列表分配索引超出范围,为什么?(Python)

2024-10-01 15:47:09 发布

您现在位置:Python中文网/ 问答频道 /正文

问题: Calculate the mean and standard deviation of a tightly clustered set of 1000 initial conditions as a function of iteration number. The bunch of initial conditions should be Gaussian distributed about x = 0.3 with a standard deviation of 10-3

我写的代码:

from numpy import *

def IterateMap(x,r,n):
    for i in xrange(n):
        x = r * x * (1.0 - x)
    return x

output = "data"
nIterations = 1000
r = 4.0
x0 = 0.3
delta = 0.00005

L = []

for i in xrange(nIterations):
    x = x0
    x = IterateMap(x,r,1)
    L[i] = x
    x0 = x0 + delta

A = array(L)

print 'mean: ', mean(A)

所以我的代码应该做的是为x(x0)取一个初始值,调用IterateMap函数,返回一个新的x值并将它放入一个list(L)中,然后x0变为一个新值,这个过程持续1000次。我得到错误“列表分配索引超出范围”。另外,你认为我正确地理解了这个问题吗?在


Tags: of代码informeanconditionsstandardinitial
2条回答

问题在于:

L = [] # the list is empty!

for i in xrange(nIterations):
    ...
    L[i] = x

要修复,请将L[i] = x替换为L.append(x)。在

当您寻址的索引超过当前大小时,Python列表不会自动增长。您创建了一个空列表,因此不能在其中寻址任何索引。在

使用.append()将新值添加到列表末尾:

L.append(x)

或者,您必须创建一个列表,该列表可以保存要生成的所有索引,方法是预先填充一个或另一个默认值:

^{pr2}$

相关问题 更多 >

    热门问题