0

I want to store a node object (Containing stuff like a x & y coordinate as well as a state) in a 2 dimensional array so I can access the object like this:

array_variable[x, y]

Unfortunatly, I do not know how to do this in python as I am quite new to it. Here is the relevant code:

class node:    
    def init(self, x, y, state):
        self.x = x;
        self.y = y;
        self.state = state;

from node import node;

class grid:
    def init(self, x, y):
        self.width = x;
        self.height = y;
        self.g = [x, y];


    def set_node(self, x, y, state):
        print(len(self.g));
        n = node();
        n.init(x, y, state);
        self.g[x][y] = n;
2
  • I fixed your indentation, but init needs to be __init__ Commented Apr 12, 2019 at 23:37
  • Semicolons at the end of the lines are not necessary in Python. Commented Apr 12, 2019 at 23:39

2 Answers 2

3

You can use Numpy for that purpose by defining the data type as object:

import numpy as np

array = np.empty((3, 3), dtype=object)
array[0, 0] = Node(...)
Sign up to request clarification or add additional context in comments.

Comments

0

You can declare a 2d array with height y and width x filled with zeros using list comprehension like this:

foo = [[0 for _ in range(x)] for _ in range(y)]

You can store node objects to position y, x in this 2d array like this:

n = node()
foo[y][x] = n

You can access the object in position y, x from 2d array like this:

node = foo[y][x]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.