If you encounter Python multi-dimensional array code in the Python initialization language to release Python multi-dimensional array related operation solutions, you will be very angry when you study the computer, you can click on our article to view it. This article involves Python multi-dimensional array initialization code to publish Python multi-dimensional array method sample code.
In Python, initialize an array of 5x3 and each item is 0. The best method is:
- multilist = [[0 for col in range(5)] for row in range(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'
The output result of print multi is:
- [['Love China', 0, 0, 0, 0], ['Love China', 0, 0, 0, 0],
['Love China', 0, 0, 0, 0]]
We modified multi [0] [0], but modified our
- multi[1][0],multi[2][0]
-
Also modified. This is not the expected result. If we write it like this:
- multilist = [[0] * 5 for row in range(3)]
- multilist[0][0] = 'Love China'
Print multilist:
- multi[1][0],multi[2][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 = [[0 for col in range(5)] for row in range(3)]
The above article is the Python multi-dimensional array initialization code release python multi-dimensional array method sample code