2011-09-03 129 views
8

如果由於某種原因,我想重複相同的迭代,我可以如何在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 

現在當功能喚醒從睡眠狀態後一天(市場(外匯交易市場)是打開的),我想繼續我的for循環從eachId = 10noteachId = 11,因爲eachId = 10尚未被處理爲market was closed ,非常感謝任何幫助。

+0

將內容保存到列表中。 – JBernardo

+0

我想他要問的是如何在一次迭代中不增加'for'循環列表計數器。 – bcoughlan

回答

18

做這樣的:

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來完成。

+0

感謝您的幫助,嵌套而ahhh如何這不是我的想法:p –

3

使用while循環?

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

只是不增加,如果你得到'市場關閉'。

0
for eachId in listOfIds: 
    while makeRequest(eachId) == 'market is closed': 
     time.sleep(24*60*60) #sleep for one day 

正如@大衛添加,如果你不需要捕獲response

+0

這是很好,除非需要捕獲'response'。否則,這必須儘可能簡潔。 –

0
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