我正在嘗試重構由嵌套回圈組成的代碼。對于類似的重復代碼片段,我正在嘗試撰寫一個包含“繼續”的函式。回圈很長,我只想在函式中包含 if 陳述句。
def calc_indexes_for_rand_switch_on(self, switch_on, rand_time, max_free_spot, rand_window):
if np.any(self.daily_use[switch_on:rand_window[1]] != 0.001): # control to check if there are any other switch on times after the current one
next_switch = [switch_on k[0] for k in np.where(self.daily_use[switch_on:] != 0.001)] # identifies the position of next switch on time and sets it as a limit for the duration of the current switch on
if (next_switch[0] - switch_on) >= self.func_cycle and max_free_spot >= self.func_cycle:
upper_limit = min((next_switch[0] - switch_on), min(rand_time, rand_window[1] - switch_on))
elif (next_switch[0] - switch_on) < self.func_cycle and max_free_spot >= self.func_cycle: # if next switch_on event does not allow for a minimum functioning cycle without overlapping, but there are other larger free spots, the cycle tries again from the beginning
continue
else:
upper_limit = next_switch[0] - switch_on # if there are no other options to reach the total time of use, empty spaces are filled without minimum cycle restrictions until reaching the limit
else:
upper_limit = min(rand_time, rand_window[1] - switch_on) # if there are no other switch-on events after the current one, the upper duration limit is set this way
return np.arange(switch_on, switch_on (int(random.uniform(self.func_cycle, upper_limit)))) if upper_limit >= self.func_cycle \
else np.arange(switch_on, switch_on upper_limit)
這是我正在嘗試撰寫的功能。if 陳述句是主代碼中較大的 while 回圈的一部分。但是,這里給出了一個錯誤,因為沒有回圈。我該如何解決這個問題?
uj5u.com熱心網友回復:
您可以在此處回傳一個標記值,例如None并在呼叫者中處理它。
所以在你的功能中:
elif (next_switch[0] - switch_on) < self.func_cycle and max_free_spot >= self.func_cycle: # if next switch_on event does not allow for a minimum functioning cycle without overlapping, but there are other larger free spots, the cycle tries again from the beginning
return None
并像這樣使用它:
while some_condition():
# do some stuff
...
result = calc_indexes_for_rand_switch_on(switch_on, rand_time, max_free_spot, rand_window)
if result is None:
continue
...
# do stuff with result
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/464574.html
