1

I need to instantiate a large number of numpy arrays. The code snippet reads:

def computa(self):
    self.variable1 = ma.zeros([self.nx, self.ny, self.nz], dtype=float)
    self.variable2 = ma.zeros([self.nx, self.ny, self.nz], dtype=float)
    self.variable3 = ma.zeros([self.nx, self.ny, self.nz], dtype=float)

The problem is that this becomes uglier as the number of variables increases. Using a list is not a valid solution because it simply makes copies of the objects but does not instantiate the arrays.

def computa(self):
    self.variables_list = [self.variable1, self.variable2, self.variable3]
    for variables in (self.variables_list):
        variables = ma.zeros([self.nx, self.ny, self.nz], dtype=float)

Is there a pythonic way to group or loop over all the numpy arrays?

2
  • Of course using a list is a valid solution. Use append or a list comprehension, or index assignment. Commented Aug 19 at 10:01
  • Apart from the possibility to add one more dimension to the array as shown in this answer, this is not really related to NumPy. Commented Aug 19 at 10:04

2 Answers 2

2

Make an array with the an added leading dimension:

def computa(n):
    return ma.zeros((n, nx, ny, nz), dtype=float)

The nth element of this array has shape (nx, ny, nz) and serves as the index of the variable.

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

Comments

0

You can use Python setattr function when you have to initialize a number of numpy arrays as properties of a class but do not want numerous repeated lines. In your approach, loop through name or index for the variables you want and then each array will be dynamically set. For example, if you require variable1, variable2 and variable3, you can write a loop and use setattr(self, f'variable{i}', ma.zeros([self.nx, self self.ny, self.nz], dtype=float)).

import numpy.ma as ma

def computa(self):
    for i in range(1, 4):  
        setattr(self, f'variable{i}', ma.zeros([self.nx, self.ny, self.nz], dtype=float))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.