Home > Back-end >  Pythonic way for double for loop
Pythonic way for double for loop

Time:03-03

I have the following code:

import numpy as np
epsilon = np.array([[0.        , 0.00172667, 0.00071437, 0.00091779, 0.00154501],
           [0.00128983, 0.        , 0.00028139, 0.00215905, 0.00094862],
           [0.00035811, 0.00018714, 0.        , 0.00029365, 0.00036993],
           [0.00035631, 0.00112175, 0.00022906, 0.        , 0.00291149],
           [0.00021527, 0.00017653, 0.00010341, 0.00104458, 0.        ]])
Sii = np.array([19998169., 14998140.,  9997923.,  7798321.,  2797958.])
n = len(Sii)

epsilonijSjj = np.zeros((n,n))
for i in range(n):
    for j in range(n):
        epsilonijSjj[i,j] = epsilon[i][j]*Sii[j]

print (epsilonijSjj)

How can I avoid the double for loop and write the code in a fast Pythonic way?

Thank you in advance

CodePudding user response:

Numpy allow you to multiply 2 arrays directly.

So rather than define a 0 based array and populating it with the altered elements of the other array, you can simply create a copy of the other array and apply the multiplication directly like so:

import numpy as np

epsilon = np.array([[0.        , 0.00172667, 0.00071437, 0.00091779, 0.00154501],
           [0.00128983, 0.        , 0.00028139, 0.00215905, 0.00094862],
           [0.00035811, 0.00018714, 0.        , 0.00029365, 0.00036993],
           [0.00035631, 0.00112175, 0.00022906, 0.        , 0.00291149],
           [0.00021527, 0.00017653, 0.00010341, 0.00104458, 0.        ]])
Sii = np.array([19998169., 14998140.,  9997923.,  7798321.,  2797958.])

epsilonijSjj = epsilon.copy()
epsilonijSjj *= Sii

print(epsilonijSjj)

Output:

[[    0.         25896.8383938   7142.21625351  7157.22103059
   4322.87308958]
 [25794.23832127     0.          2813.31555297 16836.96495505
   2654.19891796]
 [ 7161.54430059  2806.7519196      0.          2289.97696165
   1035.04860294]
 [ 7125.54759639 16824.163545    2290.12424238     0.
   8146.22673742]
 [ 4305.00584063  2647.6216542   1033.88521743  8145.97015018
      0.        ]]

Or, just do this, which is faster because it doesn't require creating a copy of an array:

import numpy as np

epsilon = np.array([[0.        , 0.00172667, 0.00071437, 0.00091779, 0.00154501],
           [0.00128983, 0.        , 0.00028139, 0.00215905, 0.00094862],
           [0.00035811, 0.00018714, 0.        , 0.00029365, 0.00036993],
           [0.00035631, 0.00112175, 0.00022906, 0.        , 0.00291149],
           [0.00021527, 0.00017653, 0.00010341, 0.00104458, 0.        ]])
Sii = np.array([19998169., 14998140.,  9997923.,  7798321.,  2797958.])

epsilonijSjj = epsilon * Sii
  • Related