简体   繁体   English

这个python for循环和if语句的行为很奇怪

[英]This python for loop and if statement are acting strange

I was solving a problem where I needed to write a code like following: 我正在解决一个需要编写如下代码的问题:

c = [0,0,1,0,0,1,0]
for i in range(7):
    if(i<7-2 and c[i+2] == 0):
        i += 1
    print(i)

I expected output like this: 我期望这样的输出:

0
2
3
5
6

But I am getting this: 但是我得到这个:

0
2
3
3
5
5
6

But with same logic/code in C it is working fine... 但是使用C中相同的逻辑/代码,它可以正常工作...

#include<stdio.h>
int main(){
    int c[] = {0,0,1,0,0,1,0};
    int i;
    for(i=0;i<7;i++){
        if(i<7-2 && c[i+2] == 0){
            i++;
        }
        printf("%d\n",i);
    }
}

What is the reason(s) or what am I missing here? 是什么原因或我在这里想念什么?

A for i in range(7) loop in python behaves as for i in [0,1,2,3,4,5,6] . python for i in range(7)循环中for i in [0,1,2,3,4,5,6]行为与for i in [0,1,2,3,4,5,6]行为相同。 i is the values in that list, rather than an index being incremented. i是该列表中的值,而不是递增的索引。 Thus, your i += 1 doesn't do what you think it does. 因此,您的i += 1不会执行您认为的操作。

You could use a while loop to get the same behavior as the c for loop, but there's probably a more pythonic way to write it. 您可以使用while循环来获得与c for循环相同的行为,但是可能有更Python的方式来编写它。

i = 0
while i < 7:
   if(i<7-2 and c[i+2] == 0):
        i += 1
   print(i)
   i+=1

The for-in loop just assigns every member of the range to i in it's turn, it does not increment i . for-in循环仅将范围中的每个成员依次分配给i ,而不会递增i Thus, any modification you make to i is lost at the end of the loop's current iteration. 因此,您对i所做的任何修改都会在循环的当前迭代结束时丢失。

You can get the desired behavior with a while loop, but you'd have to increment i yourself: 您可以使用while循环获得所需的行为,但是您必须自己增加i

i = 0
while i < 7:
    if(i<7-2 and c[i+2] == 0):
        i += 1
    print(i)
    i += 1

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

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