这是我遇到问题的 Python 代码:
for i in range (0,10):
if i==5:
i+=3
print i
我预计输出是:
0
1
2
3
4
8
9
然而,翻译却吐槽道:
0
1
2
3
4
8
6
7
8
9
我知道一个for
循环在 C 中为变量创建一个新作用域,但对 Python 不了解。为什么值i
不改变在for
Python 中的循环,如何补救才能获得预期的输出?
See How to modify list entries during for loop? for how to modify the original sequence. In 3.x, of course, range
creates an immutable object, so it would still not work.
for 循环迭代中的所有数字range(10)
, 那是,[0,1,2,3,4,5,6,7,8,9]
.
你改变current的价值i
对范围内的下一个值没有影响。
您可以通过 while 循环获得所需的行为。
i = 0
while i < 10:
# do stuff and manipulate `i` as much as you like
if i==5:
i+=3
print i
# don't forget to increment `i` manually
i += 1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)