HFL
HFL

Reputation: 13

Running same function for different arguments in a loop in python

I have large 3D same-sized array of data like density, temperature, pressure, entropy, … . I want to run a same function (like divergence()) for each of these arrays. The easy way is as follows:

div_density = divergence(density)
div_temperature = divergence(temperature)
div_pressure = divergence(pressure)
div_entropy = divergence(entropy)

Considering the fact that I have several arrays (about 100), I'd like to use a loop as follows:

var_list = ['density', 'temperature', 'pressure', 'entropy']
div = np.zeros((len(var_list)))
for counter, variable in enumerate(var_list):
    div[Counter] = divergence(STV(variable))

I'm looking for a function like STV() which simply changes "string" to the "variable name". Is there a function like that in python? If yes, what is that function (by using such function, data should not be removed from the variable)? These 3D arrays are large and because of the RAM limitation cannot be saved in another list like:

main_data=[density, temperature, pressure, entropy]

So I cannot have a loop on main_data.

Upvotes: 1

Views: 952

Answers (2)

Lukr
Lukr

Reputation: 794

how about using a dictionary? that links the variable content to names. Instead of using variable names density = ... use dict entries data['density'] for the data:

data = {} 
# load ur variables like:
data['density'] = ...

divs = {}
for key, val in data.items():
   divs[key] = divergence(val)

Since the data you use is large and the operations you try to do are computational expensive I would have a look at some of the libraries that provide methods to handle such data structures. Some of them also use c/c++ bindings for the expensive calculations (such as numpy does). Just to name some: numpy, pandas, xarray, iris (especially for earth data)

Upvotes: 0

Sankar Mantripragada
Sankar Mantripragada

Reputation: 163

One workaround is to use exec as follows

var_list = ['density', 'temperature', 'pressure', 'entropy']
div = np.zeros((len(var_list)))
for counter, variable in enumerate(var_list):
    s = "div[counter] = divergence("+variable+")"
    exec(s)

exec basically executes the string given as the argument in the python interpreter.

Upvotes: 2

Related Questions