使用python的for语句时如何跳转一些步骤

chy*_*ENG 5 python for-loop

昨天有一个面试,当我写python代码来实现一些算法时,我有一个问题。使用 C 可以像这样实现一些逻辑:

void get_some_num(int a[], int length) {       
   int i;
   for(i = 0; i < length - 1; ++i) {
       if(something) i++; // jump a num in the array
       a[i] = 1;
   }
    return some_num;
 }
Run Code Online (Sandbox Code Playgroud)

C语言i += n在for循环中使用语句迭代数组时可以跳过一些元素(如n),但我发现优雅地使用python的for语句很难实现。

我该怎么做?

ees*_*ada 7

如果您想以类似于 的方式执行此操作C,则只需使用while循环(毕竟任何for循环实际上只是while循环的特化):

i = 0
end = 10

while i < end:
    # NOTE: do something with i here

    if i == 5:
        i += 3
    i += 1
Run Code Online (Sandbox Code Playgroud)

或者您可以显式地创建并推进迭代器(我发现它的可读性要差得多):

it = iter(range(0, 10))

for i in it:
    if i == 5:
        for j in range(0, 3):
            i = next(it)
    print(i)
Run Code Online (Sandbox Code Playgroud)


idj*_*jaw 5

Python 还支持继续“跳过步骤”并继续循环。

在 for 循环中使用它:

for i in range(0, 10):
    if i == 5:
        continue
    # will never print 5
    print(i)
Run Code Online (Sandbox Code Playgroud)

如果你想让它在你的迭代中跳过一些索引,那么你可以用一个 while 循环来做这样的事情:

x = range(0, 10)
i = 0
while i <= len(x):
    if i == 5:
        i += 3
        continue
    print(i)
    i += 1
Run Code Online (Sandbox Code Playgroud)

输出:

0
1
2
3
4
8
9
10
Run Code Online (Sandbox Code Playgroud)