我知道,如果您當前正在遍歷該列表,則無法從列表中刪除元素。我想要做的是從列表中複製我不希望移除到另一個列表中的元素,然後用新列表替換原始列表。這裏是我的相關代碼:奇怪的行爲從Python中的循環中的列表中刪除元素
while len(tokenList) > 0:
# loop through the tokenList list
# reset the updated token list and the remove flag
updatedTokenList = []
removeFlag = False
for token in tokenList:
completionHash = aciServer.checkTaskForCompletion(token)
# If the completion hash is not the empty hash, parse the information
if completionHash != {}:
# if we find that a task has completed, remove it from the list
if completionHash['Status'] == 'FINISHED' and completionHash['Error'] == '':
# The task completed successfully, remove the token from the list
removeFlag = True
elif completionHash['Status'] == 'RUNNING' and completionHash['Error'] == '':
# The task must still be running
print('Task ' + completionHash['Type'] + ' ' + token + ' has been running for ' + completionHash['Runtime'] + ' seconds.')
elif completionHash['Status'] == 'queued':
# The task is in the queue
print('Task ' + completionHash['Type'] + ' ' + token + ' is queued in position ' + completionHash['QueuePosition'])
elif completionHash['Status'] == 'not_found':
# Did not find a task with this token, possible the task hasn't been added yet
print(completionHash['Error'])
# if the task is still running, no change to the token list will have occured
else:
# This is probably because the server got rid of the token after the task completed
print('Completion hash is empty, something went wrong.')
tokenListError.append(token)
removeFlag = True
if not removeFlag:
print('appending token to updatedTokenList')
updatedTokenList.append(token)
print('length of tokenList after removal loop: ' + str(len(updatedTokenList)))
# wait some time, proportional to the number of tasks left
checkInterval = len(updatedTokenList) * checkIntervalMultiplier
print('Waiting ' + str(checkInterval) + ' seconds before checking again...')
print('Tokens remaining: ' + str(len(updatedTokenList)))
# replace the original token list with the updated token list
tokenList = updatedTokenList
# wait a while based on how many tokens remain
time.sleep(checkInterval)
因此,所有這一切的重點是更新tokenList與新列表。每次循環時,新任務都已完成,不應將其添加到updatedTokenList。剩下的任務令牌將會替換原始的令牌列表。
這不起作用。在我第一次通過時,即使尚未完成任務,它也不會將任何標記添加到updatedTokenList。我無法弄清楚我做錯了什麼。有什麼建議麼?
對於初學者,您應該在循環的每次迭代開始時將'removeFlag'重置爲'False'。這可能是第一項任務已完成,並且由於'removeFlag'永遠不會重置爲'False',所以您將刪除所有任務。如果這不能解決您的問題,請嘗試單步執行代碼並查看checkTaskForCompletion()返回的內容,驗證您是否擁有正確的if條件。 – acattle 2013-05-03 01:29:51