跳过循环中的多次迭代

2025-03-20 08:46:00
admin
原创
42
摘要:问题描述:我有一个循环中的列表,我想在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大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   2482  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1533  
  PLM(产品生命周期管理)项目对于企业优化产品研发流程、提升产品质量以及增强市场竞争力具有至关重要的意义。然而,在项目推进过程中,范围蔓延是一个常见且棘手的问题,它可能导致项目进度延迟、成本超支以及质量下降等一系列不良后果。因此,有效避免PLM项目范围蔓延成为项目成功的关键因素之一。以下将详细阐述三大管控策略,助力企业...
plm系统   0  
  PLM(产品生命周期管理)项目管理在企业产品研发与管理过程中扮演着至关重要的角色。随着市场竞争的加剧和产品复杂度的提升,PLM项目面临着诸多风险。准确量化风险优先级并采取有效措施应对,是确保项目成功的关键。五维评估矩阵作为一种有效的风险评估工具,能帮助项目管理者全面、系统地评估风险,为决策提供有力支持。五维评估矩阵概述...
免费plm软件   0  
  引言PLM(产品生命周期管理)开发流程对于企业产品的全生命周期管控至关重要。它涵盖了从产品概念设计到退役的各个阶段,直接影响着产品质量、开发周期以及企业的市场竞争力。在当今快速发展的科技环境下,客户对产品质量的要求日益提高,市场竞争也愈发激烈,这就使得优化PLM开发流程成为企业的必然选择。缺陷管理工具和六西格玛方法作为...
plm产品全生命周期管理   0  
热门文章
项目管理软件有哪些?
曾咪二维码

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

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

云端的项目管理软件

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

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

内置subversion和git源码管理

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

免费试用