2016-07-27 103 views
4

Python中是否有方法將迭代計數器自動添加到while循環中?在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'(https://docs.python.org/2/library/functions.html#enumerate)此確實爲'for'循環,但我的除了你所擁有的東西以外,不知道任何'while'的解決方案。 –

+0

不幸的是,Python [不允許](https://docs.python.org/2/faq/design.html#why-can-ti-use-an-assignment-in-an-expression)賦值語句一種表達。否則,這可能會更清潔。 –

回答

9

最徹底的方法可能是將它轉換爲一個無限循環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)