def evolve():
global pop,fvals
for g in xrange(0,gmax):
for i in xrange(0,NP):
while 1:
r1=random.randint(0,NP-1)
if r1!=i:
break
while 1:
r2=random.randint(0,NP-1)
if r2!=r1 and r2!=i:
break
while 1:
r3=random.randint(0,NP-1)
if r3!=r2 and r3!=r1 and r3!=i:
break
U=[]
V=[]
for j in xrange(0,dim):
U.insert(j,(pop[r3])[j] + F*((pop[r1])[j]-(pop[r2])[j]))
jrand = floor(int(rand1()*dim))
for j in xrange(0,dim):
if rand1()<=cr or j==jrand:
U.insert(j,(pop[r3])[j] + F*((pop[r1])[j]-(pop[r2])[j]))
else:
U.insert(j,(pop[i])[j])
V.insert(i,U)
fvals2.insert(i,fun(U))
x=open("x.out","w")
for i in xrange(NP):
for j in xrange(dim):
print i
print j
x.write(str((V[i])[j]) + '\t')
x.write(str(fvals2[i]))
x.write('\n')
执行此代码块时显示错误:
x.write(str((V[i])[j]) + '\t')
IndexError: list index out of range
在这里我取了gmax=5
、dim=2
和NP=5
。你知道吗
您正在将每个
for n in xrange(0,NP)
循环上的V
设置为[]
,丢失了以前的值。这意味着在编写文件时,V
只包含一个值(最多),这就是为什么当您试图从中读取xrange(NP)
值时,会得到一个索引器。您可能希望在该循环之外初始化V
。你知道吗您在
if rand1()<=cr or j==rand
上也丢失了一些缩进,但我猜这是在将代码放入您的文章时发生的,或者在编写文件时,它可能运行的距离不足以获取索引器。你知道吗除此之外,请考虑以下几点:
x.close()
,或者在with open('x.out','w') as x:
块中完成所有写入操作。您还在for g in xrange(0,gmax)
的每个循环上覆盖该文件,因此您可能也希望将其移到该循环之外。你知道吗相关问题 更多 >
编程相关推荐