我正在尝试在for loop
中创建一个while loop
,并且需要在while loop
时破坏外部idx = 3
,但是由于某些原因,它不起作用
arr = [-1, -1, -1, -1, -1]
indices = [0, 1, 2, 3, 4]
idx = 0
while idx < 3:
for item in indices:
arr[item] = idx
idx += 1
print('idx', idx)
预期输出:
idx 1 idx 2 idx 3
实际输出:
idx 1 idx 2 idx 3 idx 4 idx 5
有什么我想念的吗?
答案 0 :(得分:1)
答案 1 :(得分:1)
我建议在其中使用break语句:
while idx < 3:
for item in indices:
arr[item] = idx
idx += 1
print('idx', idx)
if (idx >=3):
break
答案 2 :(得分:0)
可以:
<Input.Field
name="name"
label="some text"
tooltip={
<p>
Hello
<a href="www.helloworld.com">World</a>
</p>
/>
请注意,您的原始代码的实际输出是有道理的,因为arr = [-1, -1, -1, -1, -1]
indices = [0, 1, 2, 3, 4]
idx = 0
while idx < 3:
for item in indices:
arr[item] = idx
idx += 1
print('idx', idx)
if idx < 3:
continue
else:
break
是在每次迭代之前(而不是在迭代期间)进行检查的。因此,一旦确定idx < 3
确实小于3,就会发生idx
循环,这将打印并增加for
而不检查其值。如果要检查idx
并在达到某一点时停止,则必须添加我添加的子句。
答案 3 :(得分:0)
您只需要在if
中添加for
语句,然后在break
块中传递if
语句,如下所示:
arr = [-1, -1, -1, -1, -1]
indices = [0, 1, 2, 3, 4]
idx = 0
while idx < 3:
for item in indices:
arr[item] = idx
idx += 1
print('idx', idx)
if idx == 3:
break
现在,当idx
等于3
时,循环将终止。
玩得开心:)