如何强制for循环计数器跳过Python3中的迭代?

时间:2017-07-13 22:31:32

标签: python python-3.x for-loop

我最近遇到了一个问题,我使用的for循环有点类似于此:

for i in range(lineCount(fileToBeProcessed)):
    print(i)
    j = doSomeStuff() #returns number of lines in the file to skip
    i = i+j
    print(i)
    print('next_loop')

对于值j={2,3,1},输出为:

1
3
next_loop
2
5
next_loop
.
.

我想要的输出:

1
3
next_loop
4
7
next_loop
.
.

每次下一次迭代开始时,for循环计数器i都会重置为原始循环。我的问题是,有没有办法强制for循环基于返回值j跳过迭代。我理解并能够用while循环实现类似的东西。但是,我很好奇Python如何或为何不允许这样的操作?

3 个答案:

答案 0 :(得分:3)

它允许操纵。但Python中的for循环使用:

for <var> in <iterable>:
    # ...

所以Python range(n)作为for循环附加特殊含义:range(n)可迭代的0迭代到n(不包括)。在每次迭代结束时,迭代的 next 元素。它还意味着,一旦构建了range(n),如果改变n,它对for循环没有影响。这与例如Java相反,其中n每次迭代都会被评估。

因此你可以操作变量,但是在循环结束后,它将被赋予循环的下一个值。

为了操纵变量,你可以使用while循环

i = 0 # initialization
while i < lineCount(fileToBeProcessed): # while loop
    print(i)
    j = doSomeStuff() #returns number of lines in the file to skip
    i = i+j
    print(i)
    print('next_loop')
    i += 1 # increment of the for loop is explicit here

通常认为while循环不太安全&#34;因为你必须自己做增量(对于循环中的所有代码路径)。由于这是一个容易忘记的东西,所以写一个无限循环会更容易。

答案 1 :(得分:1)

假设fileToBeProcessed实际上是一个类似文件的对象,您可以直接在文件上进行迭代(即通过该文件中的行),或者如果需要行号,则使用enumerate(fileToBeProcessed),并且在该迭代器上调用next以跳过行。

像这样(未经测试):

iterator = enumerate(fileToBeProcessed) # or just iter = fileToBeProcessed
for i, line in iterator:
    print(i)
    j = doSomeStuff() #returns number of lines in the file to skip
    for _ in range(j):
        i, line = next(iterator) # advance iterator -> skip lines
    print(i)
    print('next_loop')

答案 2 :(得分:0)

我已经编辑了代码,希望对您有所帮助

z =0
for i in range(lineCount(fileToBeProcessed)):
    if i <= z: #if i is a value that you don't want to be output, then skip loop to next one
        continue
    print(i)
    j = doSomeStuff()
    cnt += 1
    z = i+j #use a different variable from i since i the iterator value will not be updated
    print(z)
    print('next_loop')
相关问题