在循环内递增 for 循环 [英] Incrementing a for loop, inside the loop

查看:32
本文介绍了在循环内递增 for 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 python 3 的循环内增加 for 循环?

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

例如:

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

如果条件成立,循环计数器 i 在哪里递增 4,否则它只会递增 1(或 for 循环的任何步长值)?

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)?

我知道 while 循环更适用于这样的应用程序,但最好知道 for 循环中的这个(或类似的东西)是否可行.

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.

谢谢!

推荐答案

你可以使用while循环并根据条件递增i:

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]`

使用 for 循环 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)

这篇关于在循环内递增 for 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆