Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在循环内递增for循环_Python_Loops_For Loop_Increment - Fatal编程技术网

Python 在循环内递增for循环

Python 在循环内递增for循环,python,loops,for-loop,increment,Python,Loops,For Loop,Increment,在Python3中,是否可以在循环内部增加for循环 例如: for i in range(0, len(foo_list)): if foo_list[i] < bar i += 4 范围内的i(0,len(foo_列表)): 如果foo_列表[i]

在Python3中,是否可以在循环内部增加for循环

例如:

for i in range(0, len(foo_list)):
    if foo_list[i] < bar
        i += 4
范围内的i(0,len(foo_列表)):
如果foo_列表[i]
如果条件为真,循环计数器
i
将增加4,否则它将只增加1(或for循环的步长值)

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

谢谢

而我while i < end:
  # do stuff
  # maybe i +=1
  # or maybe i += 4
#做事 #也许我+=1 #或者我+=4
我想如果你尝试的话,你可以在for循环中这样做,但这是不可取的。python for循环的全部要点是查看项目,而不是索引。您可以使用while循环并根据以下条件递增
i

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

在您编写的示例中,
i
将在循环的每个新迭代中重置(这似乎有点违反直觉),如下所示:

foo_list = [1, 2, 3]

for i in range(len(foo_list)):
    print('Before increment:', i)
    i += 4
    print('After increment', i)

>>>
Before increment: 0
After increment 4
Before increment: 1
After increment 5
Before increment: 2
After increment 6
continue
是跳转到循环的下一个单一迭代的标准/安全方法,但是将
continues
链接在一起要比像其他人建议的那样只使用
而使用
循环要尴尬得多。

有点黑客

>>> b = iter(range(10))
>>> for i in b:
...     print(i)
...     if i==5 : i = next(b)
... 
0
1
2
3
4
5
7
8
9
>>> 

可以使用生成器的方法通过
for
循环实现这一点,如果向生成器发送新值,则可以修改计数器:

def jumpable_range(end):
    counter = 0
    while counter < end:
        jump = yield counter
        if jump is None:
            counter += 1
        else:
            counter = jump

foo_list = [1, 2, 3, 4, 5, 6, 7, 8]
bar = 6
iterable = jumpable_range(len(foo_list))
for i in iterable:
    if foo_list[i] < bar:
        i = iterable.send(i + 4)
    print(i)

演示:

这可能是一个x y问题:我不知道为什么你不在遍历列表之前更好地处理它。再看看这个:
对于i,枚举(foo_列表)中的列表中的项目(item):print(i,列表中的项目)
我知道我的示例代码没有按预期的方式工作。我试图说明我所说的循环增量大于1的意思。谢谢你的回复!
def jumpable_range(end):
    counter = 0
    while counter < end:
        jump = yield counter
        if jump is None:
            counter += 1
        else:
            counter = jump

foo_list = [1, 2, 3, 4, 5, 6, 7, 8]
bar = 6
iterable = jumpable_range(len(foo_list))
for i in iterable:
    if foo_list[i] < bar:
        i = iterable.send(i + 4)
    print(i)
4
5
6
7