Home > Software engineering >  Python , how to convert this iterations into for loop
Python , how to convert this iterations into for loop

Time:01-04

this are the iterations

i = 0

s_array[i].append(f_array[i][i])
s_array[i].append(f_array[i 1][i])
s_array[i].append(f_array[i 2][i])

s_array[i 1].append(f_array[i][i 1])
s_array[i 1].append(f_array[i 1][i 1])

s_array[i 2].append(f_array[i][i 2])

I want to convert this iterations into for loop for example like this

for i in range(something):
        for j in range(something):
                s_array[i].append(f_array[j][i])

I tried many trial and errors, but didn't got any solution

CodePudding user response:

The equivalent iterations:

for i in range(3):
    for j in range(3 - i):
        s_array[i].append(f_array[j][i])

For example:

for i in range(3):
    for j in range(3 - i):
        print(i,"-->", j, i)
    print("")

Output:

0 --> 0 0
0 --> 1 0
0 --> 2 0
1 --> 0 1
1 --> 1 1
2 --> 0 2

CodePudding user response:

Since you are trying to append values to an array using loops, you could try nested for loops as you have indicated. Also, since you are appending fewer values as the iterations continue, you could implement a negative step value for one of the range() functions in the loops so that you iterate fewer times.

Try doing something like this:

for i in range(3):
    for j in range(3-i):
        s_array[i].append(f_array[j][i])

Hopefully, this should solve your problem.

  •  Tags:  
  • Related