The best way to initialize a 5 x 3 array of 0 per item in Python is:
multilist = [[0 for Col in range (5)] for row in range (3)]
We know that in order to initialize a one-dimensional array, we can do this:
Alist = [0] * 5
Yes, if we initialize a two-dimensional array, can we do this:
multi = [[0] * 5] * 3
In fact, this is wrong, because [0] * 5 is a one-dimensional array of objects, * 3 words just copy the object's Reference 3 times, for example, I modified multi[0][0]:
multi = [[0] * 5] * 3
Multi[0][0] = ' love China '
Print Multi
The result of the output will be:
[' Love China ', 0, 0, 0, 0], [' Love China ', 0, 0, 0, 0], [' Love China ', 0, 0, 0, 0]
We have modified multi[0][0], but we have changed our multi[1][0],multi[2][0. This is not the result we want.
If we write like this:
multilist = [[0] * 5 for row in range (3)]
Multilist[0][0] = ' love China '
Print Multilist
We look at the output:
[' Love China ', 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Yes, no problem. However, it is recommended to use the first method above, since the use of the * method is more likely to cause confusion than the bug, that is:
multilist = [[0 for Col in range (5)] for row in range (3)] can also be:
A=[0 for Col in Range (10)]
>>> A
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> a=[multilist for T in range (4)]
>>> A
[[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [[0, 0, 0, 0, 0 ], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> B=[a[i][1][1] for I in range (3)]
>>> b
[0, 0, 0]
Here, mainly for the refinement of Python, the unique simplification of processing
Python Learning notes-multidimensional arrays