简体   繁体   English

如何退出嵌套在for循环中的while循环

[英]How to exit a while loop nested in a for loop

I guess this should be simple.我想这应该很简单。 The first part of the code is to initialize the variables.代码的第一部分是初始化变量。 My problem is with the while loop.我的问题是while循环。 If the condition j == len(time) is achieved, I need to exit the WHILE loop and the FOR loop.如果条件j == len(time)达到,我需要退出 WHILE 循环和 FOR 循环。 But the thing is that once the condition is true, the while loop iterates once again;但问题是,一旦条件为真,while 循环就会再次迭代; therefore, time is out of index.因此,时间超出了索引。

import numpy as np

# Variables to initialize the problem
timeframe = 25
dt=0.025
dat=[(0, 5)]
dat.append((timeframe,dat[len(dat)-1][-1]))
time = np.arange(dat[0][0],dat[-1][0]+dt,dt)   
dat_discretized = np.zeros(len(time)) 

#While inside a for loop
j=0
for i in range(len(dat)):
    while   dat[i][0] <= time[j] <= dat[i+1][0]:
       dat_discretized[j] = dat[i][1] 
       j += 1
       print(j)
       if j == len(time):
           break

How can I exist the while loop without rechecking the while condition?如何在不重新检查 while 条件的情况下存在 while 循环?

for i in range(len(dat)):
    breakFor=false
    while   dat[i][0] <= time[j] <= dat[i+1][0]:
       dat_discretized[j] = dat[i][1] 
       j += 1
       print(j)
       if j == len(time):
           breakFor=true
           break
    if breakFor:
        break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM