循环中跳过多个迭代

2024-05-19 00:04:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个循环中的列表,我想在到达look后跳过3个元素。 在this answer中提出了一些建议,但我没有很好地利用它们:

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()是行不通的。

输出应该如下所示:

always
look
aside
of
life

Tags: ofanswer元素利用列表songonthis
3条回答
>>> 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

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

我认为,在这里使用迭代器和next是很好的:

song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
it = iter(song)
while True:
    word = next(it, None)
    if not word:
       break
    print word
    if word == 'look':
        for _ in range(4): # skip 3 and take 4th
            word = next(it, None)
        if word:
            print 'a' + word

或者,除了异常处理(正如@Steinar注意到的那样,异常处理既短又健壮):

it = iter(song)
while True:
    try:
        word = next(it)
        print word
        if word == 'look':
            for _ in range(4):
                word = next(it)
            print 'a' + word 
    except StopIteration:
        break

相关问题 更多 >

    热门问题