TypeError:“内置函数”或“方法”对象不可下标(不使用函数时)

2024-05-13 12:18:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我在执行代码时出现了这个错误。我环顾了一下其他帖子,但所有这些帖子都提到了()[]在不应该使用的地方的用法。但是,在我的例子中,我不认为这是一个问题,因为我尝试做的唯一事情就是用另一个列表的另一项覆盖一个列表的索引值。这是我试图调用它的代码:

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)

我还试图找出所使用的变量中是否有已知的函数,但这似乎也不是真的。我对这件事完全不知所措。有人能帮忙吗


Tags: ofthe代码列表错误帖子howparent
2条回答
childx = population[j].copy
childy = population[k].copy

如果您正试图使用列表的复制方法,则此操作不会执行此操作。您正在访问该方法,但没有调用它,因此childxchildy是函数

我承认我不确定为什么第一个循环没有引起这个错误

这里的问题是,您的变量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

相关问题 更多 >