我有以下程序运行400秒,并且在整个while循环中,它迭代一组时间码。当程序的经过运行时间与其中一个时间码相同时,它会执行某些操作。问题是它每秒钟多次迭代时间码数组,目前它在第二次“满足条件”时满足条件 - 我只想让它做一次......我怎么能这样做?
#!/usr/bin/env python3
import time
def get_sec(s):
l = s.split(':')
return int(l[0]) * 60 + int(l[1])
def sec_trim(s):
l = s.split('.')
return int(l[0])
times = [
'00:07',
'00:34',
'00:59',
'01:29',
'02:22',
'02:50',
'03:05',
'03:21',
'04:07',
'04:24',
'04:58',
'05:27',
'06:03',
'06:22',
'06:36',
'06:58',
'07:07',
'07:24',
'07:45',
'08:40',
'08:51',
'09:17',
'09:31',
'09:43',
'10:01',
'10:10',
'10:30',
'11:29',
'11:42',
'12:02',
'12:14',
'12:26',
'12:51',
'13:47',
'13:58',
'14:09',
'14:33'
]
start_time = time.time()
elapsed_time = time.time() - start_time
while elapsed_time < 400:
for item in times:
elapsed_time = time.time() - start_time
if get_sec(item) == sec_trim(str(elapsed_time)):
print item
# print sec_trim(str(elapsed_time))
答案 0 :(得分:2)
而不是遍历整个列表:
由于列表已排序,因此只检查第一项。
一旦达到第一项中给出的时间,请从列表中弹出。
答案 1 :(得分:0)
我没有完全理解您的问题,但如果您希望每秒运行代码序列,则可以使用time.sleep('seconds')
import time
start_time = time.time()
elapsed_time = time.time() - start_time
while elapsed_time < 400:
for item in times:
elapsed_time = time.time() - start_time
if get_sec(item) == sec_trim(str(elapsed_time)):
print item
time.sleep(1.0)
答案 2 :(得分:0)
我继续写下我在评论中提出的不同答案:
start_time = time.time()
elapsed_time = time.time() - start_time
# loop while we have times and we haven't run out of time
for next_str in times:
if elapsed_time >= 400:
break
# if there's time to kill, go to sleep
elapsed_time = time.time() - start_time
wait_time = get_sec(next_str) - elapsed_time
if wait_time > 0:
time.sleep(wait_time)
# do the thing
print next_str
# print sec_trim(str(elapsed_time))