首页 > 解决方案 > 当我们不使用彼此相同的变量时,使用 pop 方法和 for 循环之间有什么问题吗?

问题描述

当我们不使用彼此相同的变量时,使用 pop 方法和 for 循环之间有什么问题吗?

这是我的代码。

def tagsnotused(self):

    tag_list = self.Tags
    tag_list_Names = []
    # ~ append list by object Name to use index method later
    for Tag in self.Tags:
        tag_list_Names.append(Tag.Name)

    for Tag in self.Tags:   
        # ~ a = 0 tag processed, a = 1 tag not processed
        a = 0
        # ~ Adding tails
        TagName0 = Tag.Name + "."
        TagName1 = Tag.Name + "["
        TagName2 = Tag.Name + ")"
        # ~ Loop for looking conditions
        for Prog in self.Program:
            for Rout in Prog.Routine:
                for Rng in Rout.Rung:
                    # ~ Condicional para encontrar tag
                    if (Rng.Content.find(TagName0) != -1 or Rng.Content.find(TagName1) != -1 or  Rng.Content.find(TagName2) != -1) and a == 0:
                        a = 1
                        index = tag_list_Names.index(Tag.Name)
                        value = tag_list.pop(indice)
                        tag_list_Names.pop(indice)



    return tag_list 

问题是每次我进行value = tag_list.pop(indice)for 循环时都会跳过一个元素并转到下一个元素。

self.Tags如下list[_object]

标签: pythonpython-3.xlist

解决方案


您被列表的可变性所困扰。

taglist = self.Tags导致taglist指向相同的列表self.Tags

为了解决这个问题,您可以使用该copy模块。

from copy import copy

然后创建您的列表的副本,使用taglist = copy(self.Tags).

您也可以简单地使用taglist = self.Tags[:].

你的循环中发生的事情是你正在迭代self.Tags,当你从它中删除它pop()的元素时,因为它们都指向同一个对象。这会导致你的 for 循环“向前跳跃”,因为你现在少了一个元素。taglistself.Tags


推荐阅读