Python - 完全相同的循环工作不一致' int' object不可迭代 - 不迭代int

时间:2016-02-07 22:53:08

标签: python for-loop

我需要在函数中运行两次循环来执行两个不同的操作。它在一个地方工作正常,但在另一个地方无法运行,即使两者之间没有明显的区别。

这是循环

for each in problem.getSuccessors(coord): #each in [((x,y), 'Dir', num)...]

它第二次运行正常,这给了我一个几乎正确的解决方案,但是

def recursiveDFS(coord, stck, actions, visited, problem):
    repush = False
    print "ITERATE", problem.getSuccessors(coord)
    for each in problem.getSuccessors(coord): #each in [((x,y), 'Dir', num)...]
        if not each[0] in visited:
            repush = True

    if repush:
        stck.push(coord)

    if problem.isGoalState(coord):
        print coord, " is a goal state"
        return stck
    else:
        if coord in visited:
            print "revisited ", coord
        else:
            visited.append(coord)
            print "visited ", coord

        print "ITERATE", problem.getSuccessors(coord)    
        for each in problem.getSuccessors(coord): #each in [((x,y), 'Dir', num)...]
            if not each[0] in visited:
                print "PUSHED ", each
                stck.push(each)
                return recursiveDFS(each[0], stck, actions, visited, problem)

        new = stck.pop()
        print "popped ", new
        return recursiveDFS(new[0], stck, actions, visited, problem)

以下是一些详细说明错误的屏幕截图。我无法想象第一个循环和第二个循环之间有什么不同。

The second loop works fine

When I uncomment the first,似乎认为它正在迭代一个int。

有什么区别?

有关searchAgents第197行错误的一些其他信息: 这是解决函数getSuccessors,它应该返回我试图迭代的内容。它应该是(并且在第二个循环的情况下) 一个包含:[(x,y)," Direction",int]的元组,其中x和y是整数。

def getSuccessors(self, state):

    successors = []
    for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST,    Directions.WEST]:
        x,y = state
        dx, dy = Actions.directionToVector(action)
        nextx, nexty = int(x + dx), int(y + dy)
        if not self.walls[nextx][nexty]:
            nextState = (nextx, nexty)
            cost = self.costFn(nextState)
            successors.append( ( nextState, action, cost) )

    # Bookkeeping for display purposes
    self._expanded += 1 # DO NOT CHANGE
    if state not in self._visited:
        self._visited[state] = True
        self._visitedlist.append(state)

    return successors

3 个答案:

答案 0 :(得分:2)

编辑:回顾过去 问题不在for循环中,它是第一个for循环下面的部分,它将coord推入stck

if repush:
    stck.push(coord)

这只是坐标而不是each,这可能是你打算推送的,但是这意味着在函数结束时弹出它,调用它new它失败了它只是协调。我不能建议一个完整的解决方案,因为我不确定你的大部分代码是做什么的,但这就是为什么输出有" popped(3,5)"就在引发错误之前,为什么第一个元素是整数而不是坐标。

答案 1 :(得分:0)

实际错误似乎是将状态设置为int值而不是列表。检查处理状态的实际代码并初始化它。

>>> state = 34
>>> x,y = state

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    x,y = state
TypeError: 'int' object is not iterable
另一方面

>>> state = [3, 4]
>>> x,y = state
>>> print x,y
3 4

答案 2 :(得分:0)

问题不在于您的循环,而在于problem.getSuccessors(coord)返回的响应。我建议你将这个函数的结果存储在一个变量中,然后再使用该变量。这将确保您始终处理相同的事情。除非我看到problem.getSuccessors(coord)处理coord的方式,否则我无法向您提供任何其他建议。

相关问题