0

I am writing some code that uses matrices, and in some processes I want to display the matrix to console. I am storing the matrices as multidimensional lists. An assignment may look like:

mat = [[1242,2.01],[10,42.1]]

My aim is to have a function that returns a string of the array that would look like:

1242 2.01
  10 42.1

The issue is that I do not know how large the matrix will be, i.e., it will not always be 2x2, it may be a 34x84. The below code shows how I have approached this, but I feel like there must be a better way to do it.

    size = len(mat)
    for i in range(size):
        print(('{:4d} '*(size)).format(*mat[i]))

Where mat is the matrix stored as show above.

Is there a better way to do this, or is this the most pythonic way to do it?

george
  • 188
  • 12
  • 1
    If you use a `numpy.array` they will already print out formatted like that, otherwise there are many ways to [pretty print a 2d list](https://stackoverflow.com/questions/13214809/pretty-print-2d-python-list) – Cory Kramer May 03 '18 at 19:19
  • `print(np.asarray(mat))` will be your friend – Jordan May 03 '18 at 19:20
  • Better in what sense? Does the code do what you want? What do you think should be improved? Numpy and other libraries can do a good job at printing matrices but making your code depend on them just for this is not necessarily better. – Stop harming Monica May 03 '18 at 19:28
  • @Goyo so more in a sense that I've never really used .format before, and wanted to know if there is a better way to do this. I just played with he code until it did what I wanted. I'm working on a project and not using external libraries. – george May 03 '18 at 19:32

0 Answers0