How to represent a multidimensional array in Python
In Java or C and other languages, a matrix representing "Integer 3 rows and 4 columns" can be declared as: int a[3][4];
But in Python one cannot declare a variable int, and two cannot list the dimensions . We can only use the list as a list of the form.
For example, in the case of a real example, to read the data in the file in the following format, each row of data in the file is a sample, the number of columns is the number of attributes per sample. We want to read it out and combine it into a matrix of n*2 to facilitate processing of this data.
The implementation code is as follows:
DataSet = []#列表, to indicate that each element in the list is also a two-dimensional list; #这个二维列表就是一个样本. #与我们所熟悉的矩阵类似, we will eventually get a matrix of n*2, and the data for each row of elements constitutes our sample dataFilein = open ("D:/xuepython/testset.txt")#是正斜杠For lineinchFilein. ReadLines(): temp=[] Linearr = line. Strip(). Split(' \ t ')#line. Strip () remove the "\ n" at the endTemp. Append(Float (linearr[0]) Temp. Append(Float (linearr[1]) DataSet. Append(temp)#dataSet. Append ([Float (linearr[0]), float (linearr[1])) #这条语句可以替换到上面的三条语句Filein. Close()
The basic ideas above are:
(1): Finally we want the matrix DataSet to be a list of tuple.
(2): every element in a matrix temp is also a list
(3): First, we first construct each element of the temp list.
(4): Then, add each element of the Temp list (append) into the dataset.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
How to represent a multidimensional array (that is, matrix form) in Python