Skip to content
Advertisement

Matrix in python

I am very new to Python, I need to read numbers from a file and store them in a matrix like I would do it in fortran or C;

JavaScript

How can I do the same in Python? I read a bit but got confused with tuples and similar things

If you could point me to a similar example it would be great

thanks

Advertisement

Answer

Python doesn’t come with multi-dimensional arrays, though you can add them through the popular numpy third-party package. If you want to avoid third-party packages, what you would do in Python would be to use a list of lists of lists (each “list” being a 1-D “vector-like” sequence, which can hold items of any type).

For example:

JavaScript

this makes a list of 6 items which are lists of 5 items which are lists of 4 0’s — i.e., a 6 x 5 x 4 “3D matrix” which you could then address the way you want,

JavaScript

to initialize the first three of the four items on each most-nested sublist with calls to that mysterious function read which presumably you want to write yourself (I have no idea what it’s supposed to do — not “read and return the next number” since it takes a mysterious argument, but, then what?).

Advertisement