You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中修改list2后list1值改变,如何实现预期输出?

问题分析与解决方案

你的问题核心在于:Python列表的copy()方法是浅拷贝,它只会复制列表本身的结构,但列表中的字典是可变对象,浅拷贝不会复制这些字典,所以list1和list2里的字典其实是同一个对象的引用——修改list2里的字典时,list1对应的字典也会被同步改动。

把list1的初始化放到循环里依然有问题,是因为每次循环你都重新创建了list1,但最后一次循环中,你修改了浅拷贝后的list2里的字典,此时list1的字典同样会被改动,所以最终输出的list1是最后一次循环修改后的结果。

解决方法1:使用深拷贝

通过copy模块的deepcopy()方法,可以递归复制所有嵌套的可变对象,彻底切断list1和list2的引用关联:

from copy import deepcopy

list1 = [{"a":"1"}, {"b":"2"}, {"c":"3 and {a}"}]
for i in range(5, 10):
    list2 = deepcopy(list1)
    list2[-1]["c"] = list2[-1]["c"].replace("{a}", str(i))
print("List 1 is ", list1)
print("List 2 is", list2)

解决方法2:手动复制嵌套字典

如果不想引入深拷贝模块,也可以手动复制列表中的每个字典,确保list2里的字典都是新的对象:

list1 = [{"a":"1"}, {"b":"2"}, {"c":"3 and {a}"}]
for i in range(5, 10):
    # 逐个复制列表中的字典,构建新列表
    list2 = [dict(item) for item in list1]
    # 修改新列表的最后一个字典
    list2[-1]["c"] = list2[-1]["c"].replace("{a}", str(i))
print("List 1 is ", list1)
print("List 2 is", list2)

这两种方法都能让你得到预期的输出:

List 1 is  [{'a': '1'}, {'b': '2'}, {'c': '3 and {a}'}]
List 2 is [{'a': '1'}, {'b': '2'}, {'c': '3 and 9'}]

内容的提问来源于stack exchange,提问作者Vinky Senior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 00:47:23