0

I would like to be able to do something with a bunch of variables whose names are listed in an array, for example:

import numpy as np
Nsim=100
for vec in ['lgx1','lgx2','lgx3']: vec=np.random.uniform(low=0.0, high=1.0, size=Nsim)

This actually doesn't produce a compilation error, but it doesn't seem to do what I want either (i.e., doesn't set the three arrays named lgx1, lgx2 and lgx3 of random uniformly drawn variables). This would be more compact than having one such command for each of the arrays. Any suggestions? For those of us still speaking SuperMongo, I am looking for the python analog of

foreach vec {lgx1 lgx2 lgx3} {set $vec=random(100)}

Many thanks!

AlinaZ
  • 71
  • 1
  • 7

1 Answers1

5

Do not try to use variable names constructed from a variable. Instead, use a dictionary:

import numpy as np

Nsim=100
arrays = {}

for vec in ['lgx1','lgx2','lgx3']:
    arrays[vec] = np.random.uniform(low=0.0, high=1.0, size=Nsim)

Now you have arrays['lgx1'] and so on.

Or, since it looks like you are varying your "names" only by a single digit, just use a list:

lgx = []

for _ in range(3):
    lgx.append(np.random.uniform(low=0.0, high=1.0, size=Nsim))

Your arrays are now lgx[0], lgx[1], and lgx[2].

This can also be written in a single statement as a list comprehension:

lgx = [np.random.uniform(low=0.0, high=1.0, size=Nsim) for _ in range(3)]

Either way, it is now easy to work with the arrays as a group.

kindall
  • 178,883
  • 35
  • 278
  • 309