for c ++和python中的循环

g4u*_*r4v 2 c++ python for-loop

我是python的新手.我在c ++和python中有一个关于for循环的小查询.在c,c ++如果我们修改变量i,如下面的例子所示,那个新值i在下一次迭代中反映,但事实并非如此在for python中循环.所以,如果真的需要跳过一些迭代而不实际使用像continue等等的函数,如何在python中处理它.

for loop in c++

for(int i=0;i<5;++i)
{   
   if(i==2)
    i=i+2;

   cout<<i<<endl;
}
Run Code Online (Sandbox Code Playgroud)

Output

0

1

4
Run Code Online (Sandbox Code Playgroud)

for loop in python

for i in range(5):
     if i==2:
        i=i+2
     print i
Run Code Online (Sandbox Code Playgroud)

Output

0

1

4

3

4
Run Code Online (Sandbox Code Playgroud)

One*_*Pie 7

我一般建议不要在C++中修改迭代变量,因为这会使代码很难遵循.

在python中,如果你事先知道要迭代哪些值(并且它们没有太多!),你可以建立一个列表.

for i in [0,1,4]:
    print i
Run Code Online (Sandbox Code Playgroud)

当然,如果你真的必须在Python中更改迭代变量,你可以使用while循环.

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