Search code examples
pythonarraysn-dimensional

Access array[][]...[] element with N "[]" automatically


First I apologize if this question has already been asked. I've search for it but found nothing.

Given the following code :

RHO = RHOarray(D,nbInter)
    print(RHO)
    for k in range(N):
        for l in range(D):
            j=0
            Coord=[0 for i in range(D)]
            while ((X[k][l]>mini+(j+1)*step) and (j<nbInter)):
                j+=1
            Coord[l]+=j 
            RHO[ ]
for k in range(len(RHO)):
    RHO[k]/=N
return RHO  

RHO is a D-dimensions array, of size nbInter. (RHOarray is a function that creates such an array). The problem is that according to D's value, I'd need to access RHO[n] if D = 1, RHO[n][m] if D = 2 ... RHO[n][m]...[whatever indice] as D increases. Every indices would actually be Coord[0], Coord[1]... and so on, so I know what I have to put into each indices. To make the question "simpler" : how can I do so the number of "[...]" after RHO increases as much as D does ?

I hope I've been clear. I'm french and even in my native language it's still tricky to explain. Thanks in advance

ps The initial code is longer but I don't think there's need to show it entirely.


Solution

  • You could simply do something like

     indices = [1, 2, 3, 4, 5]
     value = X
    
     for i in indices:
         value = value[i]
     print(value)
    

    If X is a numpy array, you could directly do X[(1,2,3)] instead of X[1, 2, 3] or X[1][2][3]