跳过循环中的多次迭代

2025-03-20 08:46:00
admin
原创
64
摘要:问题描述:我有一个循环中的列表,我想在look到达后跳过 3 个元素。在这个答案中提出了一些建议,但我没有很好地利用它们:song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life'] for sing in song: i...

问题描述:

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

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

解决方案 1:

for用于iter(song)循环;您可以在自己的代码中执行此操作,然后在循环内推进迭代器;iter()再次调用可迭代对象将只返回相同的可迭代对象,因此您可以在循环内推进可迭代对象,并for在下一次迭代中继续进行。

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 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()

演示:

>>> 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

解决方案 2:

>>> 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

解决方案 3:

我认为,使用迭代器就很好了,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

解决方案 4:

您可以在不使用 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

解决方案 5:

当然你也可以使用三次(这里我实际上使用了四次)

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

解决方案 6:

其实,使用 .next() 三次并不是无意义的。当您想要跳过 n 个值时,请调用 next() n+1 次(不要忘记将最后一次调用的值赋给某个​​值),然后“调用” continue。

要获取您发布的代码的精确副本:

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

解决方案 7:

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

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

# this is one possible way
for sing in song:
    if sing != 'look'\n            and sing != 'always' \n            and sing != 'side' \n            and sing != 'of'\n            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
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   3970  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   2740  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Freshdesk、ClickUp、nTask、Hubstaff、Plutio、Productive、Targa、Bonsai、Wrike。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在项目管理过程中面临着诸多痛点,如任务分配不...
项目管理系统   79  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Monday、TeamGantt、Filestage、Chanty、Visor、Smartsheet、Productive、Quire、Planview。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多项目经理和团队在管理复杂项目时,常...
开源项目管理工具   87  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Smartsheet、GanttPRO、Backlog、Visor、ResourceGuru、Productive、Xebrio、Hive、Quire。在当今快节奏的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在选择项目管理工具时常常面临困惑:...
项目管理系统   74  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用