简体   繁体   English

虽然for循环内的while循环未更改python 3.x中for循环的i的值

[英]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.

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