python - 在Python循环中从列表中删除元素的奇怪行为

标签 python list

据我所知,如果您当前正在迭代该列表,则无法从列表中删除元素。然后我想做的是将我不想删除的列表中的元素复制到另一个列表,然后用新列表替换原始列表。这是我的相关代码:

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 中。剩余的任务 token 将替换原始 token 列表。

这不起作用。在我第一次通过时,即使尚未完成任何任务,它也不会向 UpdatedTokenList 添加任何 token 。我不明白我做错了什么。有什么建议吗?

最佳答案

如果将逻辑移至函数中,这会变得容易得多:

#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 ...
    ...

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

tokenList = [ token for token in tokenList if should_keep(token) ]

请注意,我们实际上并没有替换该列表。旧的列表可能仍然有对它的引用。如果您想就地替换列表,也没有问题。我们只使用切片赋值:

tokenList[:] = [ token for token in tokenList if should_keep(token) ]

关于python - 在Python循环中从列表中删除元素的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16350202/

相关文章:

python - 在 flask-reSTLess 预处理器中访问请求 header

javascript - 在同一个 View django中使用POST和GET

python - 使用 awk 从多个文件计算文件中的平均值

python - 按类型绘制 Pandas 数据框

python - 如果我在测试期间推送两个应用程序上下文,会发生什么不好的事情吗?

python - 迭代构建列表的最 Pythonic 方式?

list - 定义规则以确定列表是否包含给定成员

python - 为数字字符串创建一个指示符,忽略 python pandas 中的特定数字

list - 如何在 Scala 中制作简单的列表?

Python - 如何从字符串列表中删除字母,将字符串更改为 float ,转换一些 float 并保持顺序