为了账号安全,请及时绑定邮箱和手机立即绑定

循环内有超时的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条经验 获得超2个赞

假设单次迭代不需要那么多,只需使用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 关注
  • 87 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信