Note: This article does not detail the list in Python. You can refer to the python documentation.
Python does not have an array data structure, but the list is similar to an array, for example:
A = [0, 1, 2]
In this case, a [0] = 0, a [1] = 1, a [[2] = 2, but a problem occurs, that is, what if array a is defined as 0 to 999, in this case, a = range (0, 1000) may be used. Or omitted as a = range (1000 ). if you want to define a with a length of 1000 and the initial value is all 0, A = [0 for X in range (0, 1000)] is the definition of a two-dimensional array:
Directly define a = [[], []. Here we define a two-dimensional array of 2*2 with an initial value of 0.
Indirectly define a = [[0 for X in range (10)] for Y in range (10)]. Here we define a two-dimensional array with the initial value of 10*10 as 0.
Later, I found a simpler method to define two-dimensional arrays on the Internet:
B = [[0] * 10] * 10, which defines a two-dimensional array with the initial value of 10*10 as 0.
Compare with a = [[0 for X in range (10)] for Y in range (10)]: Print A = B returns true.
However, after B's definition method is used to replace a, the previous one can run normally.ProgramAn error also occurred. After careful analysis, the differences are obtained:
When a [0] [0] = 1, only a [0] [0] is 1, and all others are 0.
When B [0] [0] = 1, a [0] [0], a [1] [0], and only a [9, 0] is 1. Therefore, the 10 small one-dimensional data in the large array is all referenced in the same way, that is, pointing to the same address. Therefore, B = [[0] * 10] * 10 does not conform to the two-dimensional array in our general sense.
At the same time, the definition of c = [0] * 10 has the same effect as that of C = [0 for X in range (10, it is estimated that the definition of array C is a multiplication of the value type, while the previous B is a multiplication of the type, because the one-dimensional array is a reference (borrow the value type and reference type in C, ).