亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

循環內有超時的for循環?

循環內有超時的for循環?

一只萌萌小番薯 2023-06-20 17:25:57
我試圖找到一種方法來進行for循環,如果for循環的迭代次數超過超時時間,則它會中斷并轉到下一次迭代。例子 :timeout = 60for i in mylist:   i += 1   if time > timeout:       break
查看完整描述

2 回答

?
當年話下

TA貢獻1890條經驗 獲得超9個贊

我認為您可以使用時間模塊,如下所示:


import time


#get the time at the start of the program

x = time.localtime(time.time())

start_time = time.strftime('%S', x)


#the loop

timeout = 5

for i in range(10000000):

   i += 1

   y = time.localtime(time.time())

   now_time = time.strftime('%S', y)

   run_time = int(now_time) - int(start_time)

   print(run_time) #to see the run_time

   if run_time > timeout:

       break


查看完整回答
反對 回復 2023-06-20
?
一只名叫tom的貓

TA貢獻1906條經驗 獲得超3個贊

假設單次迭代不需要那么多,只需使用time模塊和 while 循環,如下所示:


mylist = [1,2,3]

import time

timeout = 60

time_start = time.time()

i = 0

while i < len(mylist) and time.time() - time_start < timeout:

    # do your stuff

    i += 1

if i == len(mylist):

    # this code runs if the iteration has completed, pass does nothing

    pass

else:

    # and this code runs if there was a timeout

    pass


查看完整回答
反對 回復 2023-06-20
  • 2 回答
  • 0 關注
  • 162 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號