这个python for循环和if语句的行为很奇怪
我正在解决一个问题,需要编写如下代码:这个python for循环和if语句的行为很奇怪,python,python-3.x,loops,Python,Python 3.x,Loops,我正在解决一个问题,需要编写如下代码: 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) 但我明白了: 0 2 3 3 5 5 6 但在C中使用相同的逻辑/代码时,它运行良好 #include<stdio.h> int main(){ int c[] = {0,0,1,0,0,1,0}; int i; fo
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)
但我明白了:
0
2
3
3
5
5
6
但在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);
}
}
#包括
int main(){
int c[]={0,0,1,0,0,1,0};
int i;
for(i=0;iAfori in range(7)
循环在python中的行为与[0,1,2,3,4,5,6]中的fori的行为相同。
是该列表中的值,而不是递增的索引。因此,i+=1
并不像您想象的那样
您可以使用while循环来获得与c for循环相同的行为,但是可能有一种更符合python的方式来编写它
i = 0
while i < 7:
if(i<7-2 and c[i+2] == 0):
i += 1
print(i)
i+=1
i=0
而我<7:
如果(ifor in循环在其循环中只将范围的每个成员分配给i
,它不会增加i
。因此,在循环的当前迭代结束时,对i
所做的任何修改都会丢失
您可以通过while
循环获得所需的行为,但您必须自己增加i
:
i = 0
while i < 7:
if(i<7-2 and c[i+2] == 0):
i += 1
print(i)
i += 1
i=0
而我<7:
如果(我非常感谢…:D非常感谢…:D
i = 0
while i < 7:
if(i<7-2 and c[i+2] == 0):
i += 1
print(i)
i += 1