How to represent a multidimensional array (that is, matrix form) in Python

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.