【问题标题】:Perform operation on the first instance of a loop that repeats forever对永远重复的循环的第一个实例执行操作
【发布时间】:2018-12-14 21:52:11
【问题描述】:

现在我有一个打算永远循环的脚本。但是,我想在第一个“圈”做一些不同的事情,如下所示:

import math

for i in range(0,math.inf):
    if i == 0:
       print("I'm gonna start the first lap")
    print('this is one lap')

"I'm gonna start the first lap"
'this is a lap'
'this is a lap'

请注意,此代码不起作用,因为 math.inf 是浮点数,而不是整数。而this post here 表示在 Python 中无法将无穷大表示为整数。

在这种情况下使用while True: 可能有意义,但是有没有办法让函数为第一次(或第x次)重复打印不同的东西?

【问题讨论】:

  • 如果你需要一个潜在的无限整数生成器——看看itertools.count

标签: python python-3.x loops for-loop


【解决方案1】:
print("I'm gonna start the first lap")
while True:
    print('this is one lap')

把它放在循环之前。

【讨论】:

    【解决方案2】:

    如果您希望在保持计数器的同时使用无限循环for,您可以使用itertools.count

    from itertools import count
    
    for i in count():
        if i == 0:
            print("I'm gonna start the first lap")
        print('This is one lap')
        # break
    

    【讨论】:

      【解决方案3】:

      这样做的明显方法是将第一次迭代放在循环之前:

      print("I'm gonna start the first lap")
      while True:
         print('this is one lap')
      

      但是,这个例子没有说明问题的其余部分。

      【讨论】:

        【解决方案4】:

        只需计算圈数并将当前圈数与所需圈数进行比较。对于第 x 次重复:

        counter = 0
        while True:
            if counter == xth:
                print("This is the xth lap")
            print('this is one lap')
            counter += 1
        

        【讨论】:

          猜你喜欢
          • 2019-12-07
          • 1970-01-01
          • 1970-01-01
          • 2017-10-28
          • 1970-01-01
          • 1970-01-01
          • 2019-06-27
          • 2012-01-09
          • 1970-01-01
          相关资源
          最近更新 更多