在while循环中计算迭代次数

6

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

我想从以下代码片段中删除count = 0count += 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)

3
您可能在想 enumerate ,它适用于 for 循环,但我不知道除了您已经使用的方式外,是否有适用于 while 循环的解决方案。 - Two-Bit Alchemist
很遗憾,Python不允许在表达式中使用赋值语句。否则,代码会更简洁易读。 - Alex W
2个回答

15

最清晰的做法可能是将它转换为无限 for 循环并将循环测试移到循环体的开头:

import itertools

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

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接