Pranav Patil
Pranav Patil

Reputation: 127

Python , how to convert this iterations into for loop

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

Upvotes: 0

Views: 96

Answers (2)

tsooone
tsooone

Reputation: 21

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.

Upvotes: 1

arshovon
arshovon

Reputation: 13651

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

Upvotes: 3

Related Questions