for使用iter(song)循环;您可以在自己的代码中执行此操作,然后在循环内推进迭代器;再次调用iterable上的iter()将只返回相同的iterable对象,这样您就可以在循环内推进iterable,并在下一次迭代中继续执行for。
使用^{} function推进迭代器;它在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)
通过移动print sing行,我们可以避免重复自己。
使用next()这样,如果iterable超出值,则可以引发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, '')
我将使用^{}跳过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), '')
表将跳过3个元素,然后返回第4个元素,然后完成。对该对象调用next(),从而从song_iter()检索第4个元素。
演示:>>> 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