The best way to initialize an array of 5 x 3 per 0 in Python is to:
Multilist = [[0 for Col in range (5)] for row in range (3)]< /c15>
We know that in order to initialize a one-dimensional array, we can do this:
Yes, so when we initialize a two-dimensional array, can we do this:
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 modify multi[0][0]:
Multi = [[0] * 5] * 3
Multi[0][0] = ' love of the '
Print Multi
The results of the output will be:
[[' Love of the ', 0, 0, 0, 0], [' Love of the ', 0, 0, 0, 0], [' Love ', 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.
What if we write this:
Multilist = [[0] * 5 for row in range (3)]
Multilist[0][0] = ' love of the '
Print multilist
Let's see the output:
[[' Love of the ', 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Yes, no problem. However, because the method of using * is more likely to cause confusion resulting in bugs, it is recommended that the first method above be used, namely:
!--
Code highlighting produced by Actipro Codehighlighter (freeware)
. CODEHIGHLIGHTER.COM/
--> multilist = [[0 for col in range ( 5 )] , for row , in range ( 3 )]