首页 > 解决方案 > Python 'int' 对象在 For 循环中不可调用

问题描述

我知道其中有很多,但是在浏览了它们之后,我无法解决我的问题。我还在学习 Python,所以可能会发生简单的混淆。

到目前为止,使用构造的 for 循环在行上达到了错误。

        # down
        column = 2
        grid = [ 10, 10 ]
        while range > 0:
            # grab at the top
            cur = genes[((grid[1] - 1) * grid[0]) + column]
            prev = cur
            for a in range((grid[1] - 2), -1, -1):
                # start one below from the top
                cur = genes[(a * grid[0]) + column]
                genes[(a * grid[0]) + column] = prev
                prev = cur
            # now apply the change back to the top
            genes[((grid[1] - 1) * grid[0]) + column] = prev
            if get_fitness(genes, grid) > fitness:
                print("After Down")
                board = Board(genes, grid)
                board.print()
                print("-------------------")
                return
            range -= 1

按照要求

Traceback (most recent call last):
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA 
Projects/Tetris/tetris.py", line 144, in test_double_block
self.solveDouble([4, 4])
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA 
Projects/Tetris/tetris.py", line 167, in solveDouble
best = genetic.get_best(fnGetFitness, None, optimalFitness, geneset, 
fnDisplay, custom_mutate=fnCustomMutate, custom_create=fnCreate, maxAge=10)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA 
Projects/Tetris/genetic.py", line 105, in get_best
maxAge, poolSize):
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA 
Projects/Tetris/genetic.py", line 131, in _get_improvement
child = new_child(parent, pindex, parents)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA 
Projects/Tetris/genetic.py", line 102, in fnNewChild
return fnMutate(parent)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA 
Projects/Tetris/genetic.py", line 74, in fnMutate
return _mutate_custom(parent, custom_mutate, get_fitness)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA 
Projects/Tetris/genetic.py", line 47, in _mutate_custom
custom_mutate(childGenes)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA 
Projects/Tetris/tetris.py", line 159, in fnCustomMutate
mutate(genes, grid, window)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA 
Projects/Tetris/tetris.py", line 65, in mutate
for a in range((grid[1] - 2), -1, -1):
TypeError: 'int' object is not callable

标签: python

解决方案


你定义range为一个数字

while range > 0:
    ... 
    range -= 1

但是你后来把它当作一个函数使用

for a in range(...):

range将整数重命名为其他名称

例如,你可以做一个向后的 for 循环

for r in range(top_range, 0, -1):
    ...

推荐阅读