值错误:解包值过多

2 投票
2 回答
9332 浏览
提问于 2025-04-16 01:19

当我运行这个程序时,它给我报了一个错误,提示是“解包的值太多了”。我该怎么做才能让它正常工作呢?

  stack = util.Stack()
  closed = []
  child = []
  index = 0
  currNode = problem.getStartState()
  node = currNode
  stack.push(node)
  while not stack.isEmpty():
     node = stack.pop()
     if problem.isGoalState(node):
        print "true"
        closed.append(node)
     else:
         child = problem.getSuccessors(node)
         for nodes in child:
            stack.push(nodes)
         closed.append(node)
  return None      

错误信息是:

 File  line 90, in depthFirstSearch
    child = problem.getSuccessors(node)
  File  line 179, in getSuccessors
    x,y = state
**ValueError: too many values to unpack**

getsuccessor函数的代码是:

def getSuccessors(self, state):
    """
    Returns successor states, the actions they require, and a cost of 1.

     """

    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) )

这个函数最开始返回的值是:

problem.getStartState() - (5, 5)
problem.isGoalState(problem.getStartState())- False
 problem.getSuccessors(problem.getStartState()) - [((5, 4), 'South', 1), ((4, 5), 'West', 1)]

2 个回答

0

不太明白为什么传给 getSuccessors 的元组大小不一致,不过你可以尝试在 node = stack.pop() 这一行之后检查一下 node 的长度。如果长度是3,那你就应该在 child = problem.getSuccessors(node) 这一行传入 node[0]

4

首先,这段代码看起来不是完整的 getSuccessors 方法,因为它没有返回值。

我猜 getSuccessors 方法应该是返回一个包含元组的列表,每个元组里有三个东西:下一个状态、动作和成本。你把这些元组当作节点存储,但当你把其中一个传回这个方法时,它会试图把三个值拆分成两个,这样就会出错。

你应该给自己找一个好用的调试工具,并学会怎么使用它。我用的是 Eclipse(配合 PyDev),这会对你解决这类错误有很大帮助。

撰写回答