当内部有嵌套的for循环时,如何停止while循环?

时间:2020-10-15 14:25:04

标签: python for-loop while-loop nested

我正在尝试在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

有什么我想念的吗?

4 个答案:

答案 0 :(得分:1)

如果等于3,您可以在第二个循环中打破一个条件

if idx == 3:
    break

编辑: 但您也可以遵循以下建议https://stackoverflow.com/a/189685/9936992

答案 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时,循环将终止。

玩得开心:)