How to define arrays in python: 1. Directly define [a=[[1,1],[1,1]]]; 2. Indirectly define [a=[[0 for x in range(10 )] for y in range(10)]]; 3. [b = [[0]*10]*10] A two-dimensional array of initial 0.
The operating environment of this tutorial: Windows 7 system, python version 3.9, DELL G3 computer.
How to define an array in Python:
There is no data structure for arrays in Python, but lists are very similar to arrays, such as:
a=[0,1,2], then a[0]=0, a[1]=1, a[[2]=2, but it raises a question, that is, if the array a wants to be defined as 0 to What to do with 999? This may be achieved through a = range(0, 1000). Or omitted as a = range(1000). If you want to define a of length 1000, and the initial values are all 0, then a = [0 for x in range(0, 1000)]
The following is Definition of two-dimensional array:
Directly define a=[[1,1],[1,1]]
, here a 2*2 is defined, and the initial A two-dimensional array of 0.
Indirect definition a=[[0 for x in range(10)] for y in range(10)]
, here defines a 10*10 two-dimensional array with an initial value of 0.
There is also a simpler method of literal two-dimensional array:
b = [[0]*10]*10
, definition 10 *10A two-dimensional array initially initialized with 0.
Compare with a=[[0 for x in range(10)] for y in range(10)]: the result of print a==b is True.
But after using the definition method of b instead of a, the program that could run normally before also went wrong. After careful analysis, the difference was found:
a[0] When [0]=1, only a[0][0] is 1, and the others are all 0.
When b[0][0]=1, a[0][0], a[1][0], until a[9,0] are all 1 .
From this we get that the 10 small one-dimensional data in the large array all have the same reference, that is, they point to the same address.
So b = [[0]*10]*10 does not conform to our conventional two-dimensional array.
Related free learning recommendations: python video tutorial
The above is the detailed content of How to define an array in python. For more information, please follow other related articles on the PHP Chinese website!