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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:05:27