Changing the number of iterations in a for loop

前端 未结 8 1346
死守一世寂寞
死守一世寂寞 2020-12-10 11:27

I have code like this:

loopcount = 3
for i in range(1, loopcount)
   somestring = \'7\'
   newcount = int(somestring)
   loopcount = newcount
8条回答
  •  独厮守ぢ
    2020-12-10 12:03

    The while-loop answer given by user802500 is likely to be the best solution to your actual problem; however, I think the question as asked has an interesting and instructive answer.

    The result of the range() call is a list of consecutive values. The for-loop iterates over that list until it is exhausted.

    Here is the key point: You are allowed to mutate the list during iteration.

    >>> loopcount = 3
    >>> r = range(1, loopcount)
    >>> for i in r:
            somestring = '7'
            newcount = int(somestring)
            del r[newcount:]
    

    A practical use of this feature is iterating over tasks in a todo list and allowing some tasks to generate new todos:

    for task in tasklist:
        newtask = do(task)
        if newtask:
            tasklist.append(newtask)
    

提交回复
热议问题