Home > Mobile >  Can a numpy array be printed, if it is tied to an instance of a class?
Can a numpy array be printed, if it is tied to an instance of a class?

Time:12-03

I am trying to create a Map(n) object, which is an n*n 2D array with random [0,1]s, and print it out.

How do I access the create_grid return value of my map1 instance, to be able to print it out?

Please be gentle, I am self-learning python, and wish to expand my knowledge.

I wish to create something like this:

map1 = Map(5) 
map1.print_grid() -> [[0,1,1,1,0]
                      [0,0,1,1,0]
                      [0,0,0,1,0]
                      [0,0,0,0,0]
                      [0,1,0,1,0]]

For now it looks like this:

class Map:
    def __init__(self, n):
        self.n = n
        self.create_grid(n)

    def create_grid(self, n):
        arr = np.random.randint(0, 2, size=(n, n))
It is needed to be converted to string, for further calculations in my program
        res = arr.astype(str)
        return res

THIS IS MY PROBLEM:

    def print_grid(self):
        for i in range(5):
            for j in range(5):
                print(res[i][j])
            print()

CodePudding user response:

Maybe you could just make a string representation of your class that uses numpy.np.array2string()

import numpy as np

class Map:
    def __init__(self, n):
        self.n = n
        self.create_grid(n)

    def create_grid(self, n):
        self.arr = np.random.randint(0, 2, size=(n, n))
        
    def __str__(self):
        return np.array2string(self.arr)

print(Map(5))

This will print something like:

[[1 1 1 0 1]
 [1 0 1 0 1]
 [1 0 0 1 1]
 [0 1 1 0 0]
 [1 0 0 0 1]]

Of course, you can wrap this in another method if you like:

   ...
    def print_grid(self):
        print(self)
    ...
Map(5).print_grid()
  • Related