执行代码时出现此错误。我浏览了有关此内容的其他文章,但所有这些文章都提到在不应使用()
或[]
的情况下。但是,就我而言,我认为唯一要解决的问题就是用另一个列表的另一个项覆盖一个列表的索引值。这是我尝试调用的代码:
def reproduce(boardx, boardy, nqueens):
boardChild = [-1] * nqueens
n = random.randint(0, nqueens - 1) #percentage of how much of one parent is reproduced and how much of the other parent
d = 0
for d in range(n): # the first n part of parent x
boardChild[d] = boardx[d]
s = d + 1
for s in range(nqueens - 1): # the last n-(len(board)-1) part of parent y
boardChild[s] = boardy[s]
return boardChild
Python当前仅给出有关此行的错误:
boardChild[s] = boardy[s]
,但不是其上方循环中的类似行。这就是我调用该函数的方式(population[j]
和population[k]
是供参考的列表):
childx = population[j].copy
childy = population[k].copy
child = reproduce(childx, childy, nqueens)
我也试图找出所使用的变量是否是已知函数,但这似乎也不是。我完全迷失了这个。有人能帮忙吗?
答案 0 :(得分:2)
childx = population[j].copy
childy = population[k].copy
如果您尝试使用列表的复制方法,则不会这样做。您正在访问方法,但未调用它,因此childx
和childy
是函数。
我承认我不确定为什么第一个循环不会引发此错误。
答案 1 :(得分:0)
这里的问题是您的变量 boardy 似乎是一个变量。如果您将该变量名称更改为其他名称,则应该可以正常工作。像这样:
def reproduce(boardX, boardY, nqueens):
boardChild = [-1] * nqueens
n = random.randint(0, nqueens - 1) #percentage of how much of one parent is reproduced and how much of the other parent
d = 0
for d in range(n): # the first n part of parent x
boardChild[d] = boardX[d]
s = d + 1
for s in range(nqueens - 1): # the last n-(len(board)-1) part of parent y
boardChild[s] = boardY[s]
return boardChild