为什么不能"i"在for循环中被操纵 [英] Why can't "i" be manipulated inside for-loop
本文介绍了为什么不能"i"在for循环中被操纵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么这样做:
for i in range(10):
i += 1
print(i)
返回:
1
2
3
4
5
6
7
8
9
10
代替:
2
4
6
8
10
?
如果需要更多详细信息,请参见此处.
Here would be some details if any more were necessary.
推荐答案
for i in range(10):
i += 1
print(i)
等同于
iterator = iter(range(10))
try:
while True:
i = next(iterator)
i += 1
print(i)
except StopIteration:
pass
iter(range(10))
产生的iterator
将在每次调用next
时产生值0
,1
,2
... 8
和9
,然后提高
The iterator
that iter(range(10))
produces will yield values 0
, 1
, 2
... 8
and 9
each time next
is called with it, then raise StopIteration
on the 11th call.
因此,您可以看到i
在每次迭代中都被range(10)
中的新值覆盖,并且没有增加,例如C风格的for
循环.
Thus, you can see that i
gets overwritten in each iteration with a new value from the range(10)
, and not incremented as one would see in e.g. C-style for
loop.
这篇关于为什么不能"i"在for循环中被操纵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文