Python中循环删除列表中元素的怪异行为

2024-05-13 18:48:50 发布

您现在位置: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添加任何标记,即使还没有完成任何任务。我不知道我做错了什么。有什么建议吗?在


Tags: thetoken列表tasklenifisstatus
3条回答

我知道您希望从列表中删除项目而不保留它们,因此,我认为您可以做的是保存与要删除的列表项对应的编号。例如,假设我有一个数字从1到5的列表,但是我只希望这个列表得到奇数,所以我想删除偶数。我要做的是设置一个带有计数器的循环,检查列表中的每一项是否符合条件(在本例中,我将检查myList[ItemNumber] % 2 == 0),如果有,我将把ItemNumber设置为另一个列表中的一个项。然后,当所有要删除的项目的编号都在这个新列表中时,我会调用另一个循环来运行这个新列表,并从另一个列表中删除新列表中包含的项目编号。是这样的:

myList = [1, 2, 3, 4, 5]
count = 0
toBeDeleted = []
while count < len(myList):
    if myList[count] % 2 == 0:
        toBeDeleted.append(count)
    count += 1

cont2 = len(toBeDeleted)
while cont2 > 0:
    cont3 = toBeDeleted[cont2 - 1]
    myList.pop(cont3)
    cont2 -= 1

这个方法很好地解决了这个问题,所以我相信并希望它能帮助你解决你的问题。在

如果将逻辑移到一个函数中,这就容易得多:

#This function should have a more descriptive name that follows your 
#project's API.
def should_keep(token):
    """returns True if the token should be kept"""
    #do other stuff here.  Possibly print stuff or whatever ...
    ...

现在,您可以用一个简单的列表理解替换列表:

^{pr2}$

请注意,我们实际上并没有替换列表。旧名单上可能仍然有它的参考。如果你想替换这个列表,那没问题。我们只使用切片分配:

^{3}$

一个问题是,在removeFlag第一次遇到应该删除的标记之后,永远不会将其设置为False。一旦它检测到一个应该删除的标记,它也将从列表中删除该标记之后的所有标记。您需要在所有completionHash elif中将其设置为False(并确保它们测试的状态值是唯一可能的),或者直接在for token in tokenlist循环中设置它。在

如果在您的测试中,第一个作业在您第一次检查完成时已经完成,那么这将与所描述的行为相匹配。在

相关问题 更多 >