for用于
iter(song)循环;您可以在自己的代码中执行此操作,然后在循环内推进迭代器;
iter()再次调用iterable只会返回相同的iterable对象,因此您可以
for在下一次迭代中紧跟着在循环内推进iterable
。
通过
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)
通过提高
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, '')
我通常会
itertools.islice()跳过3个元素;保存重复的
next()呼叫:
from itertools import islicesong = ['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), '')
该
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), '')... alwayslookasideoflife



