Nanda
Nanda

Reputation: 403

Indexing the variable in a "for" loop Python

I have the following Python code.

for i,j,k in itertools.product(range(theta),range(gamma),range(N)):
    L = (gamma[j]*math.pi)*((theta[i])**2) + x[n]

Since I have three for loops, the variable L is essentially a 3-dimensional matrix. Is it possible to index the variable L? Something like, L[i,j,k].

Upvotes: 1

Views: 483

Answers (2)

Mike67
Mike67

Reputation: 11342

If using numpy with a multi-dimensional array, you can use itertools.product to iterate across all dimensions of the array.

import numpy as np

L = np.zeros((theta, gamma, N))
for i,j,k in itertools.product(range(theta),range(gamma),range(N)):
    L[i,j,k] = (gamma[j]*math.pi)*((theta[i])**2) + x[n]

Upvotes: 1

kriss
kriss

Reputation: 24177

If what you want to get is the value of L seen as a function of i,j,k (get a specific value of L for each triplet i,j,k), the simplest way is probably to make it a hash and use a three dimensions tuple as index.

Your code would become something like that:

L = {}
for i,j,k in itertools.product(range(theta),range(gamma),range(N)):
    L[(i,j,k)] = (gamma[j]*math.pi)*((theta[i])**2) + x[k]

Beware, when done this way not all cells of "matrix" are defined, only the cells actually containing something, and you will have to manage the case when the tuple index match nothing.

Of course you can also use a numpy matrix as suggested by Mike67, the tuple trick would be most useful for cases when you don't actually loop over all possible values of theta, gamma and range but only specific interesting cases.

PS: I changed n to k in the formula as I believe it's a typo

Upvotes: 2

Related Questions