In Python, initialize an array of 5x3 and each item is 0. The best method is:
Multilist=[[0ForColInRange (5)]ForRowInRange (3)]
We know that to initialize a one-dimensional array, we can do this:
Alist=[0]* 5
Yes, can we do this when initializing a two-dimensional array:
Multi=[[0]* 5]* 3
In fact, this is not correct, because [0] * 5 is an object in a one-dimensional array, and * 3 only copies the object reference three times. For example, modify multi [0] [0]:
Multi=[[0]* 5]* 3
Multi [0] [0]= 'Love China'
PrintMultiThe output result is:
[['Love China', 0, 0, 0, 0], ['Love China', 0, 0, 0], ['Love China', 0, 0, 0, 0]
We modified multi [0] [0], but modified our multi [1] [0] and multi [2] [0. This is not the expected result.
If we write it like this:
Multilist=[[0]* 5 ForRowInRange (3)]
Multilist [0] [0]= 'Love China'
PrintMultilistThe output result is as follows:
[['Love China', 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]
Well, no problem. However, because the * method is easy to cause confusion and causes bugs, we recommend that you use the first method, namely:
Multilist=[[0ForColInRange (5)]ForRowInRange (3)]