Python列表append操作为何覆盖已有元素?技术求助
问题分析与解决
你的问题出在字典对象的引用复用上:
- 你在循环外面只创建了一个
interface_status字典,每次循环修改name值时,都是在修改同一个字典对象。 - 执行
temp_interface.append(interface_status)时,并没有把字典的内容复制一份添加到列表,而是把这个字典的内存引用加了进去。 - 所以列表里的两个元素其实指向同一个字典,最后一次循环修改了字典的
name值,列表里的所有引用都会显示这个最终值。
解决方法一:循环内新建字典
每次循环都创建一个新的字典对象,避免引用复用:
def interface(): interface_list = ['first', 'second'] temp_interface = [] for item in interface_list: interface_status = {"name": item} temp_interface.append(interface_status) print(temp_interface) interface()
解决方法二:添加字典的副本
如果需要保留外部字典的结构,每次添加时复制字典的副本到列表:
def interface(): interface_list = ['first', 'second'] temp_interface = [] interface_status = {"name": ""} for item in interface_list: interface_status['name'] = item temp_interface.append(interface_status.copy()) print(temp_interface) interface()
内容的提问来源于stack exchange,提问作者Rajesh A S
相关产品推荐
相关产品推荐

