在循环python中跳过多次迭代

时间:2014-03-10 09:05:34

标签: python loops iterator next continue

我在循环中有一个列表,我希望在达到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

7 个答案:

答案 0 :(得分:44)

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

使用next() 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()这种方式可以引发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 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) iterable将跳过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

答案 1 :(得分: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

答案 2 :(得分:4)

我认为,在这里使用迭代器和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

答案 3 :(得分:2)

实际上,使用.next()三次并不是无稽之谈。当你想要跳过n个值时,请拨打next()n + 1次(不要忘记将最后一次呼叫的值分配给某个东西)然后&#34; call&#34;继续。

获取您发布的代码的完整副本:

song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
songiter = iter(song)
for sing in songiter:
  if sing == 'look':
    print sing
    songiter.next()
    songiter.next()
    songiter.next()
    sing = songiter.next()
    print 'a' + sing
    continue
  print sing

答案 4 :(得分:2)

当然你接下来可以使用三次(这里我实际做了四次)

song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
it = iter(song)
for sing in it:
    if sing == 'look':
        print sing
        try:
           sing = it.next(); sing = it.next(); sing = it.next(); sing=it.next()
        except StopIteration:
             break
        print 'a'+sing
    else:
        print sing

然后

always
look
aside
of
life

答案 5 :(得分:2)

您可以在没有iter()的情况下执行此操作,也可以使用额外的变量:

skipcount = -1
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
for sing in song:
    if sing == 'look' and skipcount <= 0:
        print sing
        skipcount = 3
    elif skipcount > 0:
        skipcount = skipcount - 1
        continue
    elif skipcount == 0:
        print 'a' + sing
        skipcount = skipcount - 1
    else:
        print sing
        skipcount = skipcount - 1

答案 6 :(得分:0)

我相信以下代码对我来说是最简单的。

# data list
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']

# this is one possible way
for sing in song:
    if sing != 'look'\
            and sing != 'always' \
            and sing != 'side' \
            and sing != 'of'\
            and sing != 'life':
        continue
    if sing == 'side':
        sing = f'a{sing}'  # or sing = 'aside'
    print(sing)

# this is another possible way
songs_to_keep = ['always', 'look', 'of', 'side', 'of', 'life']
songs_to_change = ['side']
for sing in song:
    if sing not in songs_to_keep:
        continue
    if sing in songs_to_change:
        sing = f'a{sing}'
    print(sing)

这会产生您正在寻找的结果。

always
look
aside
of
life