2

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

4

4 Answers 4

7

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

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you this is exactly what I was looking for
@OscarWilson Just so you know . in this matrix the entire rows are the same which means modifiing one row affects all the rows so if you are dont want something like that either put list(row) or something because what is happening here is called shallow copy
I'm a little confused by this answer. Don't you want a row to have 6 cells (i.e. the number of columns)? So shouldn't it be this? row = [Cell() for i in range(num_cols)] mat = [list(row) for i in range(num_rows)]
@AlbinPaul It may have been many many years ago but I wish high school me had read this comment. I spent a very long time trying to figure out why all my Cells were changing together (I was new to programming and didn't understand object references). Makes me laugh reading it now and remembering this old project
@OscarWilson I do laugh at my old code as well. :)
|
0

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.

Comments

0

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())

4 Comments

I understand how to use nested lists however the main problem is creating a list of objects.
What do you mean with a list of objects? object_list = [Cell(), Cell(), Cell()]
Yes just like that however the size of the matrix may be a bit larger than three elements. An iterative method would be useful. I will update the question to clarify this
Using append could be an option?
0
Size = 20
Matrix = np.zeros((Size, Size))

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.