Python version 3.6.7 was tested
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.6.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: board = [[''] * 3 for i in range(3)]
In [2]: print(board)
[['', '', ''], ['', '', ''], ['', '', '']]
In [3]: board[1][2] = "X"
In [4]: print("change",board)
change [['', '', ''], ['', '', 'X'], ['', '', '']] # 可以看到x已经被赋值
In [5]:
Here is an unexpected version
In [7]: weird_board = [['_'] * 3] * 3
In [8]: print(weird_board)
[['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
In [9]: weird_board[1][2] = '0'
In [10]: print(weird_board)
[['_', '_', '0'], ['_', '_', '0'], ['_', '_', '0']] # 这里应该是改变一个数据 但是改变了每个都改变了
In [11]:
Misinterpretations
Error code outside of a list actually contains three references to the same list. When we do not modify
the time, it looks okay. Once we tried to mark the first two elements of the first row, on the very spot exposed 3 in the list
a reference point to the fact that the same object.
to sum up:
If we generate a list of actions to be sure to use for i in range () or use an iterative manner, if you use * the way Python will generate a list point to the same address, a change to change all.