无法更新字典

时间:2016-10-10 18:45:11

标签: python dictionary

我在尝试编写数独求解器时遇到此问题(某些部分引用http://norvig.com/sudoku.html

以下是我到目前为止参考上述网址所做的代码。

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,这是原始值。 (即突变不成功)

我不确定为什么会这样:(

1 个答案:

答案 0 :(得分:1)

您再次调用该函数,因此它返回一个新字典。您需要将第一次调用的结果分配给变量并改变它。

public class Instrument {
    @JsonProperty("one")
    private String myPropOne;
    @JsonProperty("two")
    private String myPropTwo;
    @JsonProperty("three")
    private String myPropThree;
}