我在尝试编写数独求解器时遇到了这个问题(其中一些部分引用了 http://norvig.com/sudoku.html )
这是我迄今为止引用上述 URL 编写的代码。
puzzle = '003198070890370600007004893030087009079000380508039040726940508905800000380756900'
cell = '123456789'
cell_break = ['123','456','789']
def generate_keys(A, B):
"Cross product of elements in A and elements in B."
return [a+b for a in A for b in B]
#print generate_keys(cell,cell)
def dict_puzzle(puzzle,cell):
'Making a dictionary to store the key and values of the puzzle'
trans_puzzle = {}
key_list = generate_keys(cell,cell)
i=0
for x in puzzle:
trans_puzzle[str(key_list[i])] = x
i = i + 1
return trans_puzzle
dict_puzzle(puzzle,cell)['11'] = 'die'
print dict_puzzle(puzzle,cell)['11']
对于代码的最后两行,我尝试更改字典但无济于事。它只是返回 0,这是原始值。 (即突变未成功)
我不知道为什么会发生这种情况:(
最佳答案
您再次调用该函数,因此它返回一个新字典。您需要将第一次调用的结果分配给一个变量并改变它。
result = dict_puzzle(puzzle,cell)
result['11'] = 'die'
print(result)
关于python - 无法更新词典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39964791/