How to change for-loop iterator variable in the loop in Python?

后端 未结 5 1566
旧巷少年郎
旧巷少年郎 2021-01-22 05:02

I want to know if is it possible to change the value of the iterator in its for-loop?

For example I want to write a program to calculate prime factor of a number in the

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-22 05:37

    Short answer (like Daniel Roseman's): No

    Long answer: No, but this does what you want:

    def redo_range(start, end):
        while start < end:
            start += 1
            redo = (yield start)
            if redo:
                start -= 2
    
    redone_5 = False
    r = redo_range(2, 10)
    for i in r:
        print(i)
        if i == 5 and not redone_5:
            r.send(True)
            redone_5 = True
    

    Output:

    3
    4
    5
    5
    6
    7
    8
    9
    10
    

    As you can see, 5 gets repeated. It used a generator function which allows the last value of the index variable to be repeated. There are simpler methods (while loops, list of values to check, etc.) but this one matches you code the closest.

提交回复
热议问题