【问题标题】:How to break cycle after a specific number of iterations in itertools?如何在 itertools 中进行特定次数的迭代后打破循环?
【发布时间】:2020-10-14 22:50:23
【问题描述】:

我有一个重复的循环,我希望它在重复 5 次后停止重复:

from itertools import cycle
a = [1,2,3]

for i in cycle(a):
    print (i)
    if i == 5:
       break

我期望的是123,123,123,123,123。它在断裂前循环了 5 次。相反,它会一直持续下去。在继续下一个代码之前,我该如何让它只循环 5 次?

【问题讨论】:

  • The docs 显示一个等效的生成器函数 - 您可以使用它并在 while 循环中添加一个计数器。
  • 您可以使用itertools.repeat 例如:for i in repeat([1, 2, 3], 5):
  • @AndrejKesely 您应该将其发布为答案。

标签: python python-3.x itertools cycle


【解决方案1】:

itertools 在此处提供所有工具;只需包裹islice 以限制输出数量(在本例中为输入数量的五倍):

from itertools import cycle, islice
a = [1,2,3]

for i in islice(cycle(a), 5*len(a)):  # Loops 15 times with a single value each time
    print(i)

# Or equivalently:
from itertools import chain, repeat

for i in chain.from_iterable(repeat(a, 5)):
    print(i)

如果您只想将 a 的全部内容重复 3 次(在每个循环中获取 [1, 2, 3] 而不是 1,然后是 2,然后是 3),您可以使用 repeat

from itertools import repeat
a = [1,2,3]

for x in repeat(a, 5):  # Loops five times, producing the same list over and over
    print(x)

【讨论】:

    【解决方案2】:

    在您的示例中,i 是列表a 中的值之一,并且永远不能是5。你应该使用enumerate 来处理这些事情:

    from itertools import cycle
    a = [1,2,3]
    
    for index, element in enumerate(cycle(a)):
        print (element)
        if index == 5 * len(a) - 1:
           break
    

    【讨论】:

    • 哦,你们都说得对。我误读了这个问题。现已修复。
    【解决方案3】:

    您可以像@Selcuk 在他的回答中提到的那样使用枚举,也可以使用next 来逐步迭代迭代器,直到它达到给定的迭代次数。

    import itertools
    n = 5
    
    a = [1,2,3]
    g = itertools.cycle(a)
    
    for i in range(n*len(a)):
        print(next(g))
    

    您也可以查看itertools.repeat() -

    import itertools
    n = 5
    
    a = [1,2,3]
    for i in itertools.repeat(a, 5):
        for j in i:
            print(j)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      • 2021-03-13
      • 1970-01-01
      • 2013-12-14
      • 2017-10-04
      • 2023-03-25
      相关资源
      最近更新 更多