When creating a two-dimensional array in which the values of all elements are 0 and counting up each element, if you specify a column with a certain row and update the value, the same column of all rows will be updated. I've done it, so I'll keep it as a memorandum so that I won't get hooked on the same place in the future.
By doing the following, a two-dimensional array of 4 rows and 10 columns can be created.
array2D = [[0] * 10] * 4
For example, if you update the values in the 3rd row and 5th column as shown below, ...
array2D[2][4] += 1
The fifth column of every row has been updated.
[[0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0]]
If you make it like the above, the array of each row will be the same.
You can do this.
array2D = [[0] * 10, [0] * 10, [0] * 10, [0] * 10]
However, it's not smart, so I think it's better to make it like this.
array2D = [[0] * 10 for _ in range(4)]
Recommended Posts