我在编写代码时遇到麻烦,不胜感激。 我的问题是,尽管列表似乎足够大,但我无法从列表中调用元素。错误是
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)
因此该代码尚不应该打印任何内容,但是在运行时会引发错误。
再次感谢您可以给我的任何帮助或意见
答案 0 :(得分:0)
win1不够大。在import scala.util.Try
Try("1234".toLong).getOrElse(-1L) // 1234L
Try("lOZ1".toLong).getOrElse(-1L) // -1L
的第一次迭代中,您正在访问它的1个位置索引for i in range(1,ts)
,但是win1的长度仅为1,因此它只有0个位置索引win1[1]
。