简体   繁体   English

更改代码块内 for 循环的迭代器

[英]Changing the iterator of the for loop inside the code block

Suppose I have a code block like,假设我有一个代码块,例如,

for i in range(15):
    print(i)
    i+=5

I expect the i value at each iteration should be i = 0,5,10, ....我希望每次迭代的 i 值应该是 i = 0,5,10, ....

Even though I am changing the iterator inside the code block of for loop, the value is not affecting the loop.即使我在 for 循环的代码块中更改迭代器,该值也不会影响循环。

Can anyone explain the functionality happening inside?谁能解释里面发生的功能?

Here, you're defining i as a number from 0 to 14 everytime it runs the new loop.在这里,您将i定义为每次运行新循环时从014的数字。 I think that what you want is this:我认为你想要的是这样的:

i = 0
for _ in range(15):
    print(i)
    i += 5

A for loop is like an assignment statement. for循环就像一个赋值语句。 i gets a new value assigned at the top of each iteration, no matter what you might do to i in the body of the loop.无论您在循环体中对i做什么, i都会在每次迭代的顶部分配一个新值。

The for loop is equivalent to for循环等价于

r = iter(range(15))
while True:
    try:
        i = next(r)
    except StopIteration:
        break
    print(i)
    i += 5

Adding 5 to i doesn't have any lasting effect, because i = next(r) will always be executed next.将 5 添加到i没有任何持久效果,因为i = next(r)将始终在下一个执行。

As the others have said, range emits the number and your assignment doesn't matter.正如其他人所说, range会发出数字,而您的分配无关紧要。

To get the desired result use something like要获得所需的结果,请使用类似

for i in range(0, 15, 5):
    print(i)

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

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