我有一个循环列表,look到达后我想跳过3个元素。在此答案中,提出了一些建议,但我未能充分利用它们:
look
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
四次continue当然是胡说八道,而四次next()是行不通的。
continue
next()
输出应如下所示:
always look aside of life
for用于iter(song)循环;您可以在自己的代码中执行此操作,然后在循环内推进迭代器;iter()再次调用iterable只会返回相同的iterable对象,因此您可以for在下一次迭代中紧跟着在循环内推进iterable 。
for
iter(song)
iter()
通过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阵容,我们也可以避免重复自己。
print sing
如果可迭代的值超出范围,则使用next()这种方法 会 引发StopIteration异常。
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()呼叫:
itertools.islice()
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), '')
该islice(song_iter, 3, 4)迭代将跳过3个元素,然后返回4,然后来完成。next()因此,调用该对象会从中检索第4个元素song_iter()。
islice(song_iter, 3, 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