计算while循环中的迭代次数 [英] Count iterations in while loop

查看:93
本文介绍了计算while循环中的迭代次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中是否有一种方法可以自动将迭代计数器添加到while循环中?

Is there a way in Python to automatically add an iteration counter to a while loop?

我想从以下代码段中删除行 count = 0 count + = 1 ,但仍然能够计算迭代次数并进行测试针对布尔值所经过的<超时:

I'd like to remove the lines count = 0 and count += 1 from the following code snippet but still be able to count the number of iterations and test against the boolean 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)

推荐答案

最干净的方法可能是将其转换为无限的 for 循环,然后将循环测试移至主体的开头:

The cleanest way is probably to convert this to an infinite for loop and move the loop test to the start of the body:

import itertools

for i in itertools.count():
    if time.time() - start >= timeout:
        break
    ...

这篇关于计算while循环中的迭代次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆