简体   繁体   中英

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. If the condition j == len(time) is achieved, I need to exit the WHILE loop and the FOR loop. But the thing is that once the condition is true, the while loop iterates once again; 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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