How to grab a certain number of dimensions from a list based off a variable

Viewed 21

I'm currently working on a python project with bunch of nested for loops and an n-dimensional array, called lst. For the first for loop I want to print out lst[i], for the second for loop I want to print out lst[i][j]. This continues until I reach the nth dimension. How do I go about this without manually adding brackets?

what I have right now looks something like this...

for i in lst:
    print(lst[i])
    for j in lst:
        print(lst[i][j])
        for k in lst:
            print(lst[i][j][k])
.
.
.

Thanks for your help!

1 Answers
def f(lst,dim,idx):
  if(len(dim)-1==idx):
     return
  print(lst[dim[idx]])
  f(lst[dim[idx]],dim,idx+1)
lst = [[1,2,3],[4,5,6]]
dim = [i,j] 
f(lst,dim,0)

I think this recursion function can use to solve your problem. dim is the (i,j,k) you mentioned in problem.I recursively go through dimensions and print each dimension results.

Related