【发布时间】:2021-02-15 02:56:39
【问题描述】:
所以,我对 Python 还很陌生,大约 6 个月;但我知道列表占用相同的内存,除非您从旧列表中复制新列表...
但是我在使用列表时看到了奇怪的行为...尝试从 csv 加载数据帧,然后转换为列表;最终目的是确保我有一个模板可以用作基础。
从 template.xlsx 加载模板
创建新的列表数据行 默认为模板的新行 更新新行 将新行添加到主控 然后在将结果写入新的 CSV 之前重复此部分。
excel_IND_TEMPLATE_df = pd.read_excel('template.xlsx',
sheet_name='IND_TEMPLATE', dtype=str)
excel_IND_TEMPLATE_df.fillna('', inplace=True)
ind_template = excel_IND_TEMPLATE_df.loc[0:0, :].values.tolist()
## using list
ind_template_copy1 = list(ind_template)
ind_template[0][0] = 'test1'
print(ind_template)
print(ind_template_copy1)
## using .copy()
ind_template_copy2 = ind_template.copy()
ind_template[0][0] = 'test2'
print(ind_template)
print(ind_template_copy2)
## using slice
ind_template_copy3 = ind_template[:]
ind_template[0][0] = 'test3'
print(ind_template)
print(ind_template_copy3)
这会输出以下内容:-
[['test1', 'Y']]
[['test1', 'Y']]
[['test2', 'Y']]
[['test2', 'Y']]
[['test3', 'Y']]
[['test3', 'Y']]
所以本质上使用列表,.copy 和 slice 都强制新列表与原始列表具有相同的内存......?我认为这会起作用...并以 2 个单独的列表结尾??
【问题讨论】:
-
见 stackoverflow.com/questions/17246693/… 和/或 stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list 。这里的一切都按预期工作:您创建了一个新列表,但列表中的项目本身实际上是相同的对象,因此当您更新它们时,您会在原始列表和副本中看到它们更新。你需要一个 deepcopy 来递归地创建新的、独立的对象。
标签: python pandas list copy slice