简体   繁体   English

Python,如何将此迭代转换为 for 循环

[英]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 循环,例如这样

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我尝试了许多试验和错误,但没有得到任何解决方案

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: Output:

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

Since you are trying to append values to an array using loops, you could try nested for loops as you have indicated.由于您正在尝试使用循环将 append 值转换为数组,因此您可以按照您的指示尝试嵌套 for 循环。 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.此外,由于您在迭代继续时附加的值较少,因此您可以为循环中的 range() 函数之一实现负步长值,从而减少迭代次数。

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.希望这应该可以解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM