Python列表追加异常:原有元素被覆盖的问题排查与解决
问题分析与解决
你遇到的问题是:运行代码后,total里的所有子列表内容完全一致,每次新追加的内容会覆盖原有子列表。先看你的代码:
import csv total = list() temp_list_helper = list() with open('divider.csv') as file_obj: reader_obj = csv.reader(file_obj) for row in reader_obj: for a in row: temp_list_helper.append(int(a)) total.append(temp_list_helper) print(total) temp_list_helper.clear()
错误原因
Python里的列表是可变对象,你在循环外只创建了一个temp_list_helper列表对象,每次往total里追加的都是这个对象的引用,不是新的列表。当你调用temp_list_helper.clear()时,这个唯一的列表内容被清空;下次循环添加新元素时,所有指向它的引用(也就是total里的所有子列表)都会同步看到新内容。最后循环结束,所有子列表其实都是指向同一个列表对象,内容自然完全一致。
解决方法
有两种简单的修复方式:
方法1:每次循环新建临时列表
把临时列表的创建放到循环内部,这样每次循环都会生成一个全新的列表对象,避免引用复用:
import csv total = list() with open('divider.csv') as file_obj: reader_obj = csv.reader(file_obj) for row in reader_obj: temp_list_helper = list() # 每次循环新建列表 for a in row: temp_list_helper.append(int(a)) total.append(temp_list_helper) print(total)
方法2:追加临时列表的副本
如果想保留循环外的临时列表定义,可以在追加时复制一份列表的副本,这样total里存储的是独立的列表对象:
import csv total = list() temp_list_helper = list() with open('divider.csv') as file_obj: reader_obj = csv.reader(file_obj) for row in reader_obj: for a in row: temp_list_helper.append(int(a)) total.append(temp_list_helper.copy()) # 追加副本 print(total) temp_list_helper.clear()
也可以用list(temp_list_helper)代替temp_list_helper.copy(),效果一样。
内容的提问来源于stack exchange,提问作者Knm
相关产品推荐
相关产品推荐

