蟒蛇错误"IndexError: list assignment index out of range"



我在代码方面遇到麻烦,并且会喜欢与任何意见有关的评论。我的问题是,我无法从列表中调用元素,尽管在我看来,列表已经足够大了。错误是

Traceback (most recent call last):
  File "BrownM.py", line 126, in <module>
    optim1(pbias,x,i,nbias,stock1,cash1)
  File "BrownM.py", line 88, in optim1
    win1[i] = cash1[i] - cash1[i-1]
IndexError: list assignment index out of range

我不太了解问题在哪里。也许我使用的是" .Append"太多?

代码类似:

import numpy as np
p0 = []
p0.append(0)
p0[0]=1000.00
ts=10               
dx = 1.0
x = np.random.uniform(0.0,dx)
pbias= np.random.uniform(1.0, 50.0)
nbias= np.random.uniform(0.0, 1.0)
cash1 = []
cash1.append(1)
cash1[0]=100000.0
cash4 = []
cash4.append(1)
cash4[0]=100000.0
stock1=0
stock4=0
win1 = []
win4 = []
def optim1(pbias,x,i,nbias, stock1,cash1):
    if p0[i] <= p0[i-1] + pbias*x :
        stock1= stock1 + 1
        cash1[i] = cash1[i-1] - p0[i]

    elif p0[i] > p0[i-1] + pbias*x :
        if stock1 > 0:
            stock1 = stock1-1
            cash1[i] = cash1[i-1] + p0[i]
    win1[i] = cash1[i] - cash1[i-1]

def pesim1(pbias,x,i,nbias, stock4,cash4):
    if p0[i] < p0[i-1] - nbias*x :
        stock4= stock4 + 1
        cash4[i] = cash4[i-1] - p0[i]
    elif p0[i] >= p0[i-1] - pbias*x:
        if stock4 > 0:
            stock4 = stock4-1
            cash4[i] = cash4[i-1] + p0[i]
    win4[i] = cash4[i] - cash4[i-1]

for i in range(1,ts):
    p0.append(i)
    p0[i] = p0[i-1]
    cash1.append(i)
    win1.append(i)
    cash4.append(i)
    win4.append(i)
    optim1(pbias,x,i,nbias,stock1,cash1)
    pesim1(pbias,x,i,nbias,stock4,cash4)

因此,代码还不应打印任何东西,但是运行时会引发错误。

再次感谢您的任何帮助或评论,您可以给我

win1不够大。在for i in range(1,ts)的第一次迭代中,您是访问其1个位置索引win1[1],但Win1的长度仅为1,因此它只有0位置索引,win1[0]

相关内容

最新更新