Scope of python variable in for loop

前端 未结 10 1955
一整个雨季
一整个雨季 2020-11-22 15:16

Heres the python code im having problems with:

for i in range (0,10):
    if i==5:
        i+=3
    print i

I expected the output to be:

10条回答
  •  天涯浪人
    2020-11-22 16:10

    If for some reason you did really want to change add 3 to i when it's equal to 5, and skip the next elements (this is kind of advancing the pointer in C 3 elements), then you can use an iterator and consume a few bits from that:

    from collections import deque
    from itertools import islice
    
    x = iter(range(10)) # create iterator over list, so we can skip unnecessary bits
    for i in x:
        if i == 5:             
            deque(islice(x, 3), 0) # "swallow up" next 3 items
            i += 3 # modify current i to be 8
        print i
    
    0
    1
    2
    3
    4
    8
    9
    

提交回复
热议问题