Search code examples
pythonlist-comprehensionenumerate

Iterating through multiple variables while performing a calculation and saving result? List comprehension, enumerate() - Python


I have a range of temperatures ('T') (0 - 100 inclusive) and a range of humidities ('RH') (0-1.00 inclusive) so 101 values in each list.

For each step through temp I would like to run a calculation for the range of humidities, so at T=0 I calculate for every RH in the list and save the results of each calculation (returns an np.array), then at T=1 repeat calc for entire range of RH again and save each result and so on...

I am using list comprehension to iterate over the two lists:

ray2 = np.zeros(np.size(T)*np.size(RH))
ray18 = np.zeros(np.size(T)*np.size(RH))

for x,y in [(x,y) for x in T for y in RH]:

    ray2, ray18 = rayleigh(T[x], RH[y], f, del2, del18)

I cannot figure out how to incorporate a counter into the list comprehension to save all 10201 results as an array.


Solution

  • I think you need to create n by m zeros matrix, then save all the data to it

    ray2 = np.zeros((np.size(T), np.size(RH)))
    ray18 = np.zeros((np.size(T), np.size(RH)))
    
    for idx, t_ele in enumerate(T):
        for idx_rh, rh_ele in enumerate(RH):
    
            ray2[idx][idx_rh], ray18[idx][idx_rh] = rayleigh(t_ele , rh_ele , f, del2, del18)