Count iterations during a loop

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

I would like to delete the line count = 0and count += 1in the following code fragment, but still be able to count the number of iterations and test using 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)
+4
source share
2 answers

The cleanest way, probably, is to convert this to an infinite loop forand move the loop test to the beginning of the body:

import itertools

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

Instead, you can move the while loop to the generator and use 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)
+3
source

Source: https://habr.com/ru/post/1649326/


All Articles