Oscar Wilson
Oscar Wilson

Reputation: 59

Creating a matrix of objects in python

I need to make a matrix of objects in python. I have found other solutions in various languages however cannot find a reliable and efficient method to do this in python.

Given the class

class Cell():
    def __init__(self):
        self.value = none 
        self.attribute1 = False
        self.attribute2 = False

I want to make a matrix of multiple 'cells' as efficiently as possible. Since the size of the matrix will be larger than 20 by 20, an iterative method would be useful. Any contributions are helpful

Upvotes: 2

Views: 12302

Answers (4)

C.Nivs
C.Nivs

Reputation: 13106

Update for correctness

The numpy.full answer will copy the single existing Cell(), giving your references to one object. Use a list comprehension here:

row = [[Cell() for _ in range(num_cols)] for _ in range(num_rows)]

Old answer

If you already have defined your objects, list comprehensions can help here:

num_rows = 5
num_cols = 6

row = [Cell() for i in range(num_cols)]
# The original way doesn't behave exactly right, this avoids 
# deep nesting of the array. Also adding list(row) to create
# a new object rather than carrying references to row to all rows
mat = [list(row) for i in range(num_rows)]

#[[Cell(), Cell(), Cell()...], [...], ..., [Cell(), ..., Cell()]]

You can wrap them in numpy.array if you want to as well

NumPy array full

You could also use the numPy full method which is built-in and generates an n by m numpy array filled with your values:

mat = numpy.full((num_rows, num_cols), Cell())

The documentation can be found here

Upvotes: 7

Guimoute
Guimoute

Reputation: 4629

Size = 20
Matrix = np.zeros((Size, Size))

for x in range(0, Size):
    for y in range(0, Size):
        Matrix[x][y] = Cell()

Upvotes: 0

grouchoboy
grouchoboy

Reputation: 1024

Maybe just using nested lists?

Something like:

mtx = [[0, 1, 2], [3, 4, 5]]
mtx[1][1] # 4

Edit: You can add elements to a list using the append method.

the_list = []
for item in iterator_or_something:
    the_list.append(Cell(item.a, item,b))

If it is a fixed size and you know it:

the_list = []
for x in range(0, 500):
    the_list.append(Cell())

Upvotes: 0

berkelem
berkelem

Reputation: 2115

If you know in advance what size your matrix is you could initialize a numpy array using np.empty or np.zeros and then fill in the cells using indexing.

Or you could append items to lists and then convert to an array by np.array(list). You'll want your matrix as a numpy array for any calculations you do.

Upvotes: 0

Related Questions