【问题标题】:Key k returned by dict.keys() causes KeyError when doing dict[k]: KeyError on existing keydict.keys() 返回的键 k 在执行 dict[k] 时导致 KeyError: KeyError on existing key
【发布时间】:2017-09-26 04:59:13
【问题描述】:

以下代码

for k in list(g_score.keys()):
    print(g_score[k])

为我返回一个KeyError

Traceback (most recent call last):
  File "./np.py", line 134, in <module>
    main()
  File "./np.py", line 131, in main
    NPuzzle(n).solve()
  File "./np.py", line 116, in solve
    print(g_score[k])
KeyError: 3

print(list(g_score.keys()))[4, 3, 7] 时,我不明白这怎么可能。 3 显然在字典中。


对于上下文,我正在尝试对 N-Puzzle 问题实施 A* 搜索(我什至不确定 A* 是否正确实施,因为我无法克服此错误),并且有以下State 类和solve 函数:

class State:
    def __init__(self, blank_idx, puzzle, g=0, h=0):
        self.blank_idx = blank_idx
        self.puzzle = puzzle
        self.f = g + h

    def __eq__(self, other):
        return self.puzzle == other.puzzle

    def __hash__(self):
        return self.f + self.blank_idx

    def __lt__(self, other):
        return self.f < other.f

    def __repr__(self):
        return str(self.f)

...

class NPuzzle:

    # ...other stuff

    def solve(self):
      start_state = State(
          self.puzzle.index(' '),
          self.puzzle,
          0,
          self.cost(self.puzzle)
      )

      g_score = {start_state: 0}
      open_set = [start_state]
      path = {}

      while open_set:
          state = open_set[0]

          if state.puzzle == self.goal_state:
              break

          heappop(open_set)
          for next_state in self.neighbors(state):
              g = g_score[state] + 1
              if next_state in g_score and g >= g_score[next_state]:
                  continue

              path[next_state] = state
              g_score[next_state] = g
              next_state.f = g + self.cost(next_state.puzzle)
              heappush(open_set, next_state)

我第一次遇到的错误发生在我所在的行上:

g = g_score[state] + 1

我不确定为什么会发生这种KeyError,但我假设它可能与我的自定义__hash()__ 函数有关。

【问题讨论】:

  • 我将__hash__的定义替换为__hash__ = object.__hash__。并且没有错误,但也永远不会终止。所以问题似乎真的是由哈希函数引起的。虽然我不知道如何根据您的目的实现此哈希函数,但您可以使用默认哈希函数使其工作。

标签: python python-3.x dictionary keyerror


【解决方案1】:

好吧,原来问题是我立即更改了哈希函数所依赖的State 实例的属性...哎呀:

State__hash()__ 函数是:

return self.f + self.blank_idx

我在g_score 中存储State 的方式如下:

g_score[next_state] = g
next_state.f = g + self.cost(next_state.puzzle)

原来上面的内容破坏了一切,因为它使用next_state.fnext_state 放入g_score,但随后在下一行我立即改变了next_state.f

像这样切换两个语句的顺序:

next_state.f = g + self.cost(next_state.puzzle)
g_score[next_state] = g

解决了我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-23
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 2021-01-06
    • 2013-12-16
    • 2014-09-09
    相关资源
    最近更新 更多