python - 为什么这个 python 列表不在循环中分配它的值?
问题描述
当通过端口的循环运行时,变量 afc_rem 仅在第一个循环中设置为 all_fields,然后当值被删除时,它永远不会重新获得 all_fields 的完整列表。为什么会这样?
if __name__ == "__main__":
all_fields = ["byr","iyr","eyr","hgt","hcl","ecl","pid","cid"]
ports = ["byr iyr"...]
for port in ports:
afc_rem = all_fields
for field in afc_rem:
if field in port:
afc_rem.remove(field)
解决方案
解释
基本上,当你分配afc_rem = all_fields
thenafc_rem
只是内存中的一个引用,这意味着那afc_rem
仍然指向all_fields
. 您可以通过执行内部循环来观察这一点:
print(id (afc_rem))
print( id ( all_fields))
因此,在从中删除项目时afc_rem
也会从 中删除项目all_fields
。
解决方案:
尝试深拷贝:
import copy
afc_rem = copy.deepcopy(all_fields)
推荐阅读
- sql - 在 sql plus 中显示错误
- ios - 使用 AVAssetExportSession 后视频颜色错误
- javascript - nodejs 断言模块:assert.throws 只返回“未定义”
- c# - 如何在不为每个方法添加一行的情况下“记录”
- html - 使用 HTML 在 CSS 中添加背景图像
- python - 从 docker 内部,激活驻留在主机上的 Python 虚拟环境
- java - Jackson XmlMapper 映射嵌套元素的 XML 属性
- database - 我应该将上传的文件名存储在数据库中吗?
- python - 如何用另一个词替换文本中的某些词
- amazon-web-services - 在哪里可以查看服务在 AWS ECS 中使用的放置策略?