Calling arrays within a list in python

1k views Asked by At

I have healpy maps of the Cosmic Microwave Background. Each map has three fields. I have written the following function within a code to calculate the power spectrum of the first field of a general number of maps:

def ps_TT(files):
c=[]
for i in range (0, len(files)):
    #reads each map in turn
    lmap=hp.read_map(files[i], field=(0,1,2))
    #calculates the power spectra for all fields for each map
    cl_lmap=hp.sphtfunc.anafast(lmap)
    #selects the first field of the power spectra calculated for each map
    cl_TT=cl_lmap[0]
    #puts the results in the list c
    c.append(cl_TT)
return c

the 'files' input is an array of the map filenames as strings. The above code returns the following output for 10 maps in ipython:

In [4]: print ps_TT
[array([  5.17445252e-04,   1.14526987e-03,   1.73325663e+03, ...,
     2.38082865e-04,   2.50555631e-04,   2.53376503e-04]), array([  1.45351786e-02,   6.01176345e-03,   1.27994240e+03, ...,
     2.45848964e-04,   2.57155084e-04,   2.61421094e-04]), array([  1.50848754e-03,   1.20842536e-02,   4.24761289e+02, ...,
     2.56162191e-04,   2.47074545e-04,   2.58200020e-04]), array([  7.59059129e-04,   1.40839130e-03,   1.00377030e+03, ...,
     2.56563612e-04,   2.52381965e-04,   2.49896550e-04]), array([  5.13876807e-04,   2.05938986e-02,   2.90047155e+02, ...,
     2.53182443e-04,   2.50890172e-04,   2.50914303e-04]), array([  1.54646117e-02,   6.75181707e-03,   1.90852416e+03, ...,
     2.42936214e-04,   2.60074106e-04,   2.40752858e-04]), array([  2.24837030e-02,   1.25850426e-03,   1.68506209e+03, ...,
     2.51372591e-04,   2.45068513e-04,   2.50685742e-04]), array([  2.16127178e-03,   6.70720310e-03,   1.55092736e+03, ...,
     2.56133055e-04,   2.55980054e-04,   2.47690501e-04]), array([  3.62577651e-05,   2.76265910e-03,   1.39297592e+03, ...,
     2.64044826e-04,   2.67847727e-04,   2.56234516e-04]), array([  7.69252941e-03,   4.32015790e-04,   1.34833309e+03, ...,
     2.42188570e-04,   2.53480172e-04,   2.42193006e-04])]

This has 10 arrays within a list. Each array has the first field power spectrum data for a particular map. What I want to be able to do is call individual arrays within this list in my code so as to perform a function on each individual array of data.

I looked at the pages Array within an array? and Accessing elements in a list of arrays in python but did not find either as helpful as I hoped.

1

There are 1 answers

0
ErikR On

You have a list of arrays, so just index into the list for a specific array:

myfunc( ps_TT[3] )   # call myfunc on the 4th array

or you can iterate over all of the arrays:

for i, arr in enumerate(ps_TT):
   print "Processing array", i
   ... do something with arr...