Python -- passing multiple variables from a list of names -
this question has answer here:
- how create variable number of variables? 12 answers
i able bunch of variables names listed in array, example:
import numpy np nsim=100 vec in ['lgx1','lgx2','lgx3']: vec=np.random.uniform(low=0.0, high=1.0, size=nsim)
this doesn't produce compilation error, doesn't seem want either (i.e., doesn't set 3 arrays named lgx1, lgx2 , lgx3 of random uniformly drawn variables). more compact having 1 such command each of arrays. suggestions? of still speaking supermongo, looking python analog of
foreach vec {lgx1 lgx2 lgx3} {set $vec=random(100)}
many thanks!
do not try use variable names constructed variable. instead, use dictionary:
import numpy np nsim=100 arrays = {} vec in ['lgx1','lgx2','lgx3']: arrays[vec] = np.random.uniform(low=0.0, high=1.0, size=nsim)
now have arrays['lgx1']
, on.
or, since looks varying "names" single digit, use list:
lgx = [] _ in range(3): lgx.append(np.random.uniform(low=0.0, high=1.0, size=nsim))
your arrays lgx[0]
, lgx[1]
, , lgx[2]
.
this can written in single statement list comprehension:
lgx = [np.random.uniform(low=0.0, high=1.0, size=nsim) _ in range(3)]
either way, easy work arrays group.