Python dict.keys()返回的键k在执行dict[k]:现有键上的KeyError时导致KeyError
下面的代码Python dict.keys()返回的键k在执行dict[k]:现有键上的KeyError时导致KeyError,python,python-3.x,dictionary,keyerror,Python,Python 3.x,Dictionary,Keyerror,下面的代码 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
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
我第一次遇到错误是在以下行中:
g = g_score[state] + 1
我不确定为什么会发生这个
键错误,但我假设它可能与我的自定义\uuuuuhash()\uuuuuuu
函数有关
我的\uuuuu hash()\uuuuu
状态的函数是:
return self.f + self.blank_idx
我将状态
存储在g_分数
中的方式如下:
g_score[next_state] = g
next_state.f = g + self.cost(next_state.puzzle)
事实证明,上面的代码破坏了一切,因为它使用next_state.f
将next_state
放入g_分数
,但在下一行我立即变异next_state.f
按如下方式切换两个语句的顺序:
next_state.f = g + self.cost(next_state.puzzle)
g_score[next_state] = g
修复了我的问题。我用\uuuuuu hash\uuu=object替换了\uuuuuu hash\uuuuu
的定义。没有错误,但也永远不会终止。所以这个问题似乎真的是由散列函数引起的。虽然我不知道如何根据您的目的实现这个哈希函数,但您可以使用默认的哈希函数使其工作。
g_score[next_state] = g
next_state.f = g + self.cost(next_state.puzzle)
next_state.f = g + self.cost(next_state.puzzle)
g_score[next_state] = g