Python中有没有办法自动将迭代计数器添加到while循环中?
我想从以下代码段中删除行count = 0
和count += 1
,但仍然可以计算迭代次数并针对布尔值elapsed < timeout
进行测试:
import time
timeout = 60
start = time.time()
count = 0
while (time.time() - start) < timeout:
print 'Iteration Count: {0}'.format(count)
count += 1
time.sleep(1)
答案 0 :(得分:10)
最干净的方法可能是将其转换为无限for
循环并将循环测试移动到正文的开头:
import itertools
for i in itertools.count():
if time.time() - start >= timeout:
break
...
答案 1 :(得分:3)
您可以将while循环移动到生成器并使用enumerate
:
import time
def iterate_until_timeout(timeout):
start = time.time()
while time.time() - start < timeout:
yield None
for i, _ in enumerate(iterate_until_timeout(10)):
print "Iteration Count: {0}".format(count)
time.sleep(1)