为什么Python for循环不像C for循环那样工作?

Sur*_*rya 6 c python for-loop

C:

# include <stdio.h>
main()
{
    int i;
    for (i=0; i<10; i++)
    {
           if (i>5) 
           {
             i=i-1;     
             printf("%d",i);
           } 
    }
}
Run Code Online (Sandbox Code Playgroud)

蟒蛇:

for i in range(10):
   if i>5: i=i-1
   print(i)
Run Code Online (Sandbox Code Playgroud)

当我们编译C代码时,它会永远进入无限循环打印5,而在Python中却没有,为什么不呢?

Python输出是:

0 1 2 3 4 5 5 6 7 8

drr*_*lvn 27

在Python中,循环不会递增i,而是从可迭代对象(在本例中为list)中为其赋值.因此,i在for循环内部进行更改不会"混淆"循环,因为在下一次迭代i中将简单地分配下一个值.

在您提供的代码中,当i为6时,它在循环中递减,以便将其更改为5然后打印.在下一次迭代中,Python只是将其设置为列表中的下一个值[0,1,2,3,4,5,6,7,8,9],即7,依此类推.当没有更多值时,循环终止.

当然,您在C循环中获得的效果仍然可以在Python中实现.因为每个for循环都是一个美化的while循环,从某种意义上说它可以像这样转换:

for (init; condition; term) ...
Run Code Online (Sandbox Code Playgroud)

相当于:

init
while(condition) {
    ...
    term
}
Run Code Online (Sandbox Code Playgroud)

那么你的无限循环可以用Python编写:

i = 0
while i < 10:
    if i > 5:
        i -= 1
    print i
    i += 1
Run Code Online (Sandbox Code Playgroud)


Win*_*ert 6

这两个构造都被称为循环,但它们实际上并不是同一个东西.

Python的版本实际上是一个foreach循环.它为集合中的每个元素运行一次. range(10)生成一个列表,[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]因此for循环为集合的每个成员运行一次.它不使用i决定下一个元素的值,它总是采用列表中的下一个元素.

c for循环被翻译成等价的

int i = 0
while i < 10:
   ...
   i++;
Run Code Online (Sandbox Code Playgroud)

这就是你可以操纵的原因i.