我有一个for循环如下:
i=0
while true:
print("i initialized as", i)
for i in range(0,3):
print ("inside for",i)
i = i + 1
print("exit from for i value is",i)
现在在无限循环中,每次都在内部为" i"迭代从" 0"理想情况下"我"应该获得递增的值并从2开始,输出为:
inside for 0
inside for 1
inside for 2
second iteration:
inside for 0
inside for 1
inside for 2
.
.
理想输出如下:
inside for 0
inside for 1
inside for 2
second iteration:
inside for 3
inside for 4
inside for 5
.
.
所以关键是"我"值不会保存,每次循环都从0开始,那么我该如何制作" i"在进入for循环之前从最后一个递增的值开始。
答案 0 :(得分:2)
当您使用i
时,您无法控制for i in ...
。它被设置为循环时for
循环决定的任何内容。
此处,不要使用i
作为循环索引,使用_
之类的匿名变量来计算3次,将i
保留为"全局& #34;计数器:
i=0
while i<10: # just to stop after a while for the demo
print("i initialized as", i)
for _ in range(0,3):
print ("inside for",i)
i = i + 1
print("exit from for i value is",i)
输出:
inside for 0
inside for 1
inside for 2
exit from for i value is 3
i initialized as 3
inside for 3
inside for 4
inside for 5
exit from for i value is 6
i initialized as 6
inside for 6
inside for 7
inside for 8
exit from for i value is 9
i initialized as 9
inside for 9
inside for 10
inside for 11
exit from for i value is 12
除此之外:while true
应为while True
。与Java&amp; C ++,布尔值在python中大写。
答案 1 :(得分:1)
这里的问题是您正在尝试修改for
循环的循环变量。 Python并没有阻止你在循环中执行i = i + 1
,但是一旦控制返回到循环的顶部,i
就会被重置为序列中下一个值。这就是for
循环在Python中的工作方式,如果你循环遍历列表或元组而不是range
,也会发生这种情况。例如,
for i in (2, 3, 5, 7, 11):
print(i)
i = 10 * i
print(i)
<强>输出强>
2
20
3
30
5
50
7
70
11
110
但是,要获得所需的输出很简单。在以下代码中,我使用小while
循环替换了无限for
循环。
i = 0
for j in range(3):
print("\ni initialized as", i)
for i in range(i, i + 3):
print ("inside for", i)
i += 1
<强>输出强>
i initialized as 0
inside for 0
inside for 1
inside for 2
i initialized as 3
inside for 3
inside for 4
inside for 5
i initialized as 6
inside for 6
inside for 7
inside for 8
如果外环不是无限的,你可以通过单个循环和if
测试来做这种事情。它更紧凑,但速度稍慢,因为它必须在每次循环迭代时执行测试。
outer_loops = 4
inner_loops = 3
for i in range(outer_loops * inner_loops):
if i % inner_loops == 0:
print("\nIteration", i // inner_loops)
print ("inside for", i)
<强>输出强>
Iteration 0
inside for 0
inside for 1
inside for 2
Iteration 1
inside for 3
inside for 4
inside for 5
Iteration 2
inside for 6
inside for 7
inside for 8
Iteration 3
inside for 9
inside for 10
inside for 11
答案 2 :(得分:0)
请勿覆盖i
循环中的变量for
(我将其更改为_
):
i=0
while true:
print("i initialized as", i)
for _ in range(0,3):
print ("inside for",i)
i = i + 1
print("exit from for i value is",i)
答案 3 :(得分:0)
也许这会有所帮助:
i=0
while true:
print("i initialized as", i)
for x in range(i+1, i+4):
print ("inside for",i)
i = i + 1
print("exit from for i value is",i)