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

Python修改字典列表元素时单条更新却同步修改所有索引如何解决

问题根因

你使用np.repeat()生成updated列表时,仅复制了原字典对象的内存引用,列表中所有元素指向同一个字典实例,修改任意一个元素的属性都会同步作用到所有引用指向的同一块内存空间,因此出现所有索引值同步更新的问题。

修复方案

替换np.repeat逻辑,对每个需要生成的option项做深拷贝,确保每个列表元素都是独立的字典实例:

  • 引入copy模块的deepcopy方法处理嵌套字典的深拷贝
  • 循环生成对应数量的独立option对象
完整修复代码
import copy
list_foci=["Erbschaftssteuerrecht","Erbrecht"]
list_size=len(list_foci)
dynamic_list= [
    {
      "title": "What time do you want your appointment?",
      "options": [
        {
          "label": "Monday 1:00 pm",
          "value": {
            "input": {
              "text": "Monday 1:00 pm"
            }
          }
        }
      ],
      "description": "",
      "response_type": "option"
    }
  ]
# 替换np.repeat逻辑,深拷贝生成独立的option对象
updated = [copy.deepcopy(dynamic_list[0]['options'][0]) for _ in range(list_size)]
response={
  "arr": [
    {
      "title": "Wählen Sie das passende Rechtsgebiet:",
      "options": updated,
      "description": "",
      "response_type": "option"
    }
  ]
  }
response['arr'][0]['options'][0]['label']= "Contract Law"
response['arr'][0]['options'][0]['value']['input']['text'] = "Contract Law"
response['arr'][0]['options'][1]['label']= "Sales Law"
response['arr'][0]['options'][1]['value']['input']['text'] = "Sales Law"
print(response)
运行输出验证

修改后打印的response中两个option的值为独立值,不会同步更新:

{'arr': [{'title': 'Wählen Sie das passende Rechtsgebiet:', 'options': [{'label': 'Contract Law', 'value': {'input': {'text': 'Contract Law'}}}, {'label': 'Sales Law', 'value': {'input': {'text': 'Sales Law'}}}], 'description': '', 'response_type': 'option'}]}

内容的提问来源于stack exchange,提问作者Aymal Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:15:03