繁体   English   中英

我不断收到错误列表分配索引超出范围,为什么? (蟒蛇)

[英]I keep getting the error List assignment index out of range, why? (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 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的新值并将其放在列表中(L)然后x0更改为新值,这样过程持续1000次。 我得到错误“列表分配索引超出范围”。 另外,你认为我正确地解决了这个问题吗?

当您将索引置于其当前大小之外时,Python列表不会自动增长。 您创建了一个空列表,因此无法解决其中的任何索引。

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

L.append(x)

或者,您必须创建一个列表,该列表可以包含您要生成的所有索引,方法是使用None或其他默认值预填充它:

L = [None for _ in xrange(nIterations)]

问题出在这里:

L = [] # the list is empty!

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

要修复,用L.append(x)替换L[i] = x

暂无
暂无

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

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