Home > Net >  Printing out a matrix out of a two dimensional list
Printing out a matrix out of a two dimensional list

Time:12-10

I would like to implement the str method to nicely format the string representation of the matrix: one line per row, two characters per number (-) and a space between numbers. For example:

m = Matrix([[1,0,0],[0,1,0],[0,0,1]])

print(m)

1  0  0

0  1  0

0  0  1

I've tried this:

class Matrix:
    def __init__(self, rows):
        self.rows = rows
      


    def __str__(self):
        for element in self.rows:
            for i in element:
                print(i, end=" ")
            print()

But my output becomes

1 2 3 

4 5 6
 
7 8 9 

None

How would I solve this? Because the none shouldn't be there.

CodePudding user response:

The __str__ method has to return a string, not print it. What you are seeing is:

  1. The prints inside of __str__.
  2. The return value of __str__, which is None.

To correct it, build a string in __str__ and return it.

CodePudding user response:

class Matrix:
    def __init__(self, rows):
        self.rows = rows

    def read(self):
        for element in self.rows:
            for i in element:
                print(i, end="  ")
            print('\n')


m = Matrix([[1,0,0],[0,1,0],[0,0,1]])

m.read()

You Should use something like this. Creating a new function to represent your data is good practice than trying to use the __str__ method to do your job. because you might need to handle other edge cases explicitly


Output:

1  0  0  

0  1  0  

0  0  1 

Note: This way you can remove None at the end as well

because The first is inside function and the second is outside function. When a function doesn't return anything, it implicitly returns None.

CodePudding user response:

Maybe you could do it like this?

class Matrix:
    def __init__(self, rows):
        self.rows = np.array(rows)
  
    def __str__(self):
        return "\n".join(np.array2string(row)[1:-1] for row in self.rows)

m = Matrix([[1,0,0],[0,1,0],[0,0,1]])

print(m)

Notice that we here convert rows to to a 2d numpy array first. If you want to avoid numpy for some reason, you can do this.

class Matrix:
    def __init__(self, rows):
        self.rows = rows
  
    def __str__(self):
        return '\n'.join(' '.join(map(str, row)) for row in self.rows)
 
m = Matrix([[1,0,0],[0,1,0],[0,0,1]])

print(m)
  • Related