python - 当我们不使用彼此相同的变量时,使用 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]
解决方案
您被列表的可变性所困扰。
taglist = self.Tags
导致taglist
指向相同的列表self.Tags
为了解决这个问题,您可以使用该copy
模块。
from copy import copy
然后创建您的列表的副本,使用taglist = copy(self.Tags)
.
您也可以简单地使用taglist = self.Tags[:]
.
你的循环中发生的事情是你正在迭代self.Tags
,当你从它中删除它pop()
的元素时,因为它们都指向同一个对象。这会导致你的 for 循环“向前跳跃”,因为你现在少了一个元素。taglist
self.Tags
推荐阅读
- azure-ad-b2c - 在 ID 为“AAD-UserReadUsingObjectId”策略的技术配置文件中定义的 ID 为“objectId”的查找声明找不到声明
- c# - 如何使用“Windows.Networking.NetworkOperators”获取 Esim 类对象
- swift - 点击后更改 barButtonSystemItem
- node.js - npm 错误!在“...registry.npmjs.org/@i”附近解析时 JSON 输入意外结束
- excel - 用于重新格式化数据的 Excel 宏
- javascript - 根据图像的大小有条件地设置样式属性,通过 url 获取
- c++ - 将 GTK 与 CMake 一起使用时出现“未定义的引用”
- c# - 如何组合两个整数数组并返回平均值?
- mips - 试图在 mips 的链表中工作 strcpy
- c# - 如何使用绝对布局创建自定义弹出窗口?