如何绕过“字典在迭代过程中更改大小” [英] how to bypass 'dictionary changed size during iteration'
问题描述
我正在为一个可由表(元组的元组)表示的问题写一个启发式函数,并且我从表中的一些随机单元格开始,给出0值,然后对其加1邻居等等-这个值以后可以在字典中显示-其中键是单元格的坐标,而值是其值。
I'm writing a heuristic function for a problem that can be presented by a table (a tuple of tuples) and I'm starting with some random cells in my table which I give a 0 value, then adding 1 to its neighbors and so on - this value is later can be shown in a dictionary - where the key is the cell's coords and the value is its value. everytime I get into a new cell, I save it into my dic.
问题-对于我制作的这种BFS式方法,我需要某种动态大小的字典。当我开始迭代时,有一些初始键,然后在代码运行时添加了更多初始键-代码也需要检查那些新单元格。虽然我认为python将能够处理此问题,但我遇到一个运行时错误,提示 RuntimeError:字典在迭代过程中更改了大小。
The problem - for this BFS-ish method which I made, I need some kind of a dynamic sized dictionary. There are some initial keys when I start iterating, then more are added when the code runs - and the code needs to check those new cells too. While I thought python will be able to handle this, I got a runtime error that says "RuntimeError: dictionary changed size during iteration"
visitedCells = dict()
for row in range(len(node.state)):
for cell in range(len(node.state[0])):
if STATEMENT:
visitedCells[row, cell] = 0
for cell, val in visitedCells.items():
row = cell[0]
col = cell[1]
if STATEMENT:
visitedCells[row + 1, col] = val + 1
if STATEMENT:
visitedCells[row - 1, col] = val + 1
if STATEMENT:
visitedCells[row, col + 1] = val + 1
if STATEMENT:
visitedCells[row, col - 1] = val + 1
我希望它实际改变大小并在迭代过程中继续。
I expect it to actually change size and continue during iteration. Is there any way to do this?
推荐答案
您可以维护要访问的单元格队列和单独的字典,该字典指示每个单元格的状态:
You can maintain a queue for the cells to visit and a separate dictionary which indicates the state of each cell:
queue = list(visitedCells.items())
while queue:
row, col = queue.pop(0)
if STATEMENT:
visitedCells[row + 1, col] = val + 1
queue.append((row + 1, col))
...
这篇关于如何绕过“字典在迭代过程中更改大小”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!