Changing the number of iterations in a for loop

前端 未结 8 1374
死守一世寂寞
死守一世寂寞 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:13

    To specifically address the question "How do I change the range bounds", you can take advantage of the send method for a generator:

    def adjustable_range(start, stop=None, step=None):
        if stop is None:
            start, stop = 0, start
    
        if step is None: step = 1
    
        i = start
        while i < stop:
            change_bound = (yield i)
            if change_bound is None:
                i += step
            else:
                stop = change_bound
    

    Usage:

    myrange = adjustable_range(10)
    
    for i in myrange:
        if some_condition:
            myrange.send(20) #generator is now bounded at 20
    

提交回复
热议问题