[英]While loop inside for loop is not changing value of i of for loop in python 3.x
Here is my code 这是我的代码
A = [0,0,-1,0]
for i in range(len(A)):
while (i<len(A)) and (A[i] >=0):
print(i, A[i])
i=i+1
when I am executing this code in python 3.x my output is 当我在python 3.x中执行此代码时,我的输出是
Output
0 0
1 0
1 0
3 0
My question is : When while loop exits for the first time value of i
becomes 2
since A[2] < 0
我的问题是:由于
A[2] < 0
当while循环第一次退出时, i
值变为2
But after that when it goes to parent for loop then why value of i
again becomes 1
? 但是之后,当它转到父循环时,为什么
i
值再次变为1
?
Because after that in 3rd line of output it prints 1 0
again. 因为在输出的第三行之后,它再次打印
1 0
。
Python for
loops are not like C for
loops; Python
for
循环与C for
循环不同。 the iteration value is replaced on each loop, discarding any changes made inside the loop. 迭代值将在每个循环上替换 ,并丢弃循环内所做的任何更改。 No matter what you do to
i
inside the for
loop, when the for
loop loops, you pull the next value from the iterator, so i
will always progress through all the values in the range
one at a time. 无论您在
for
循环内对i
做什么,当for
循环循环时,您都从迭代器中提取下一个值,因此i
将始终一次遍历一个range
所有值。
The 'for' statement does not work like it might in C. The i variable gets reassigned each iteration. 'for'语句无法像在C语言中那样工作。每次迭代都会重新分配i变量。
You can think of 'for i in x' as being more like: while x has more values, set i to the next value from x. 您可以将“ for i in x”想像为:x具有更多值时,将i设置为x中的下一个值。
The problem happens after the while loop exits. 该问题在while循环退出后发生。 i is set to the next value in
range(len(A))
which is 1 for the next iteration of the for loop. i设置为
range(len(A))
的下一个值,对于for循环的下一次迭代,该值为1。
You can fix this by initializing i and removing the for loop 您可以通过初始化i并删除for循环来解决此问题
A = [0,0,-1,0]
i=0
while (i<len(A)) and (A[i] >=0):
print(i, A[i])
i=i+1
Or using the break
command 或使用
break
命令
A = [0,0,-1,0]
for i in range(len(A)):
if(A[i]<0):
break
print(i, A[i])
Try running the code in any Python debugger and you'll see it all at once. 尝试在任何Python调试器中运行代码,您将立即看到它们。 The code works correctly.
该代码正常工作。 If you need a specific result, ask, I will help you.
如果您需要特定的结果,请询问,我会为您提供帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.