Home  >  Article  >  Backend Development  >  Detailed introduction to Python array definition method

Detailed introduction to Python array definition method

高洛峰
高洛峰Original
2017-03-06 14:01:492181browse

The examples in this article describe the Python array definition method. Share it with everyone for your reference, the details are as follows:

There is no data structure for arrays in Python, but lists are very similar to arrays, such as:

a=[0,1,2]

At this time: a[0]=0, a[1]=1, a[[2]=2, but it raises a question, that is, what if the array a wants to be defined as 0 to 999? This may be Implemented through a = range(0, 1000). Or omit it as a = range(1000). If you want to define a with a length of 1000, and the initial values ​​are all 0, then a = [0 for x in range(0, 1000)]

The following is a two-dimensional array Definition:

Direct definition:

a=[[1,1],[1,1]]

This defines a 2*2 two-dimensional array with an initial value of 0.

Indirect definition:

a=[[0 for x in range(10)] for y in range(10)]

This 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

Define a 10*10 two-dimensional array with an initial value of 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][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], and 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.

After testing at the same time: the definition of c=[0]*10 has the same effect as c=[0 for x in range(10)], without the problem of the same reference above, it is estimated that the definition of array c At this time, the value type is multiplied, while in the previous b, the type is multiplied, because the one-dimensional array is a reference (borrowing the value type and reference type in C#, I don’t know if it is appropriate).

For more detailed introduction to Python array definition methods and related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn