首页 > 解决方案 > 为什么这个 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)
                

标签: pythonloops

解决方案


解释

基本上,当你分配afc_rem = all_fieldsthenafc_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)

推荐阅读