在循环python中跳过多次迭代

Meh*_*len 37 python iterator loops continue next

我有一个循环列表,我想look在达到之后跳过3个元素.在这个答案中提出了一些建议,但我没有充分利用它们:

song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
for sing in song:
    if sing == 'look':
        print sing
        continue
        continue
        continue
        continue
        print 'a' + sing
    print sing
Run Code Online (Sandbox Code Playgroud)

continue当然四次是胡说八道,使用四次next()是行不通的.

输出应如下所示:

always
look
aside
of
life
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 47

for使用iter(song)循环; 你可以在自己的代码中执行此操作,然后在循环内推进迭代器; iter()再次调用iterable将只返回相同的可迭代对象,因此您可以在循环内推进迭代for,并在下一次迭代中跟随.

使用该next()函数推进迭代器; 它可以在Python 2和3中正常工作,而无需调整语法:

song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
song_iter = iter(song)
for sing in song_iter:
    print sing
    if sing == 'look':
        next(song_iter)
        next(song_iter)
        next(song_iter)
        print 'a' + next(song_iter)
Run Code Online (Sandbox Code Playgroud)

通过移动print sing线,我们也可以避免重复.

如果可迭代超出值,则使用next()这种方式可以引发StopIteration异常.

您可以捕获该异常,但是更容易给出next()第二个参数,一个默认值来忽略该异常并返回默认值:

song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
song_iter = iter(song)
for sing in song_iter:
    print sing
    if sing == 'look':
        next(song_iter, None)
        next(song_iter, None)
        next(song_iter, None)
        print 'a' + next(song_iter, '')
Run Code Online (Sandbox Code Playgroud)

我itertools.islice()用来跳过3个元素; 保存重复next()通话:

from itertools import islice

song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
song_iter = iter(song)
for sing in song_iter:
    print sing
    if sing == 'look':
        print 'a' + next(islice(song_iter, 3, 4), '')
Run Code Online (Sandbox Code Playgroud)

该islice(song_iter, 3, 4)迭代将跳过3个元素,然后返回4,然后来完成.next()因此,调用该对象将从中检索第4个元素song_iter().

演示:

>>> from itertools import islice
>>> song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
>>> song_iter = iter(song)
>>> for sing in song_iter:
...     print sing
...     if sing == 'look':
...         print 'a' + next(islice(song_iter, 3, 4), '')
... 
always
look
aside
of
life
Run Code Online (Sandbox Code Playgroud)


dem*_*o.b 6

>>> song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
>>> count = 0
>>> while count < (len(song)):
    if song[count] == "look" :
        print song[count]
        count += 4
        song[count] = 'a' + song[count]
        continue
    print song[count]
    count += 1

Output:

always
look
aside
of
life
Run Code Online (Sandbox Code Playgroud)