【问题标题】:repeat an iteration of for loop重复for循环的迭代
【发布时间】:2011-09-03 15:22:12
【问题描述】:

如果由于某种原因我想重复相同的迭代,我该如何在 python 中做到这一点?

for eachId in listOfIds:
    #assume here that eachId conatins 10
    response = makeRequest(eachId) #assume that makeRequest function request to a url by using this id
    if response == 'market is closed':
       time.sleep(24*60*60) #sleep for one day

现在,当函数在一天后从睡眠中唤醒时(市场(货币交易市场)打开)我想从 eachId = 11 恢复我的 for 循环,因为 eachId = 10 还没有已作为market was closed 处理,非常感谢任何帮助。

【问题讨论】:

  • 将内容保存到列表中。
  • 我认为他要问的是如何在一次迭代中不增加 for 循环列表计数器。

标签: python for-loop


【解决方案1】:

这样做:

for eachId in listOfIds:
    successful = False
    while not successful:        
        response = makeRequest(eachId)
        if response == 'market is closed':
            time.sleep(24*60*60) #sleep for one day
        else:
            successful = True

你的问题的标题是线索。 重复是通过迭代实现的,在这种情况下,您可以简单地使用嵌套的while

【讨论】:

  • 感谢您的帮助,嵌套而 ahhh 我怎么没想到:p
【解决方案2】:
i = 0
while i < len(listOfIds):
    eachId = listOfIds[i]
    #assume here that eachId conatins 10
    response = makeRequest(eachId) #assume that makeRequest function request to a url by using this id
    if response == 'market is closed':
       time.sleep(24*60*60) #sleep for one day
    else:
       i += 1

【讨论】:

    【解决方案3】:

    使用while 循环?

    counter = 0
    while counter < len(listOfIds):
      # do processing
      counter = counter + 1
    

    如果您得到“市场关闭”,请不要增加。

    【讨论】:

      【解决方案4】:
      for eachId in listOfIds:
          while makeRequest(eachId) == 'market is closed':
             time.sleep(24*60*60) #sleep for one day
      

      正如@David 添加的那样,如果您不需要捕获response

      【讨论】:

      • 这很好,除非response 需要被捕获。否则,这必须尽可能简洁。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 2016-10-20
      • 2013-10-15
      • 1970-01-01
      • 2013-03-23
      相关资源
      最近更新 更多