【问题标题】:Python list of list value updation not working [duplicate]列表值更新的Python列表不起作用[重复]
【发布时间】:2020-04-12 08:18:57
【问题描述】:

我有一个嵌套列表 x。内部列表以字典为元素。

y = [{'hello1': 1, 'hello2': 2, 'hello3': 3}, {'hello1': 1, 'hello2': 2, 'hello3': 3}]
x = []
for i in range(0,3):
    x.append(y)

counter = 5
for i in x:
    for j in i :
        j['hello2'] = counter
    counter = counter + 1

print(x)

我得到的输出

[
  [
    {
      'hello1': 1,
      'hello2': 7,
      'hello3': 3
    },
    {
      'hello1': 1,
      'hello2': 7,
      'hello3': 3
    }
  ],
  [
    {
      'hello1': 1,
      'hello2': 7,
      'hello3': 3
    },
    {
      'hello1': 1,
      'hello2': 7,
      'hello3': 3
    }
  ],
  [
    {
      'hello1': 1,
      'hello2': 7,
      'hello3': 3
    },
    {
      'hello1': 1,
      'hello2': 7,
      'hello3': 3
    }
  ]
]

我正在寻找的输出

[
  [
    {
      'hello1': 1,
      'hello2': 5,
      'hello3': 3
    },
    {
      'hello1': 1,
      'hello2': 5,
      'hello3': 3
    }
  ],
  [
    {
      'hello1': 1,
      'hello2': 6,
      'hello3': 3
    },
    {
      'hello1': 1,
      'hello2': 6,
      'hello3': 3
    }
  ],
  [
    {
      'hello1': 1,
      'hello2': 7,
      'hello3': 3
    },
    {
      'hello1': 1,
      'hello2': 7,
      'hello3': 3
    }
  ]
]

我希望第一个列表的 hello2 值为 5,第二个列表的 hello2 值为 6,第三个列表的 hello2 值为 7。 请向我提供有关需要进行哪些修改的有效输入。 谢谢你

【问题讨论】:

    标签: python list dictionary python-3.6


    【解决方案1】:

    字典是可变的,所以在每次迭代中你都添加同一个字典,所以每次你更新同一个字典。

    你需要复制一份:

    x.append(deepcopy(y)) 
    

    【讨论】:

      猜你喜欢
      • 2015-04-12
      • 2021-12-26
      • 1970-01-01
      • 2015-02-24
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      • 2019-10-10
      • 1970-01-01
      相关资源
      最近更新 更多