Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

python - Incrementing a for loop, inside the loop

Is it possible to increment a for loop inside of the loop in python 3?

for example:

for i in range(0, len(foo_list)):
    if foo_list[i] < bar
        i += 4

Where the loop counter i gets incremented by 4 if the condition holds true, else it will just increment by one (or whatever the step value is for the for loop)?

I know a while loop would be more applicable for an application like this, but it would be good to know if this (or something like this) in a for loop is possible.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use a while loop and increment i based on the condition:

while i < (len(foo_list)): 
    if foo_list[i] < bar: # if condition is True increment by 4
        i += 4
    else: 
        i += 1 # else just increment 1 by one and check next `foo_list[i]`

Using a for loop i will always return to the next value in the range:

foo_list = [1,2,3,4,5,6]
bar = 6
for i in range(len(foo_list)):
    print("range i ",i)
    if foo_list[i] < bar:
        i += 4
        print("if i",i)


('range i ', 0)
('if i', 4)
('range i ', 1)
('if i', 5)
('range i ', 2)
('if i', 6)
('range i ', 3)
('if i', 7)
('range i ', 4)
('if i', 8)
('range i ', 5)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...