我在 Python 字典中看到一些异常行为:
import numpy as np
td =[np.Inf, 2, 3]
a = {}
# First initialize contents of dictionary to a list of values
for k in range(10):
a[k] = td
# now I want to access the contents to modify them based on certain criteria
for k in range(10):
c = a[k]
c[0] = k
a[k] = c
据此,我希望每个字典键值的列表的每个第一项都根据 (c[0] = k
) 进行更改,但是,我最后得到的是字典的所有 值都更新为k
的最后一个值,如:
{0: [9, 2, 3], 1: [9, 2, 3], 2: [9, 2, 3], 3: [9, 2, 3],
4: [9, 2, 3], 5: [9, 2, 3], 6: [9, 2, 3], 7: [9, 2, 3],
8: [9, 2, 3], 9: [9, 2, 3]}
是我遗漏了什么,还是字典定义有问题?
我可以通过不同的方式来解决这个问题,让我的代码运行,但我很想知道为什么字典类会以这种方式运行。
最佳答案
因为每个键都得到相同的列表...要制作列表的浅拷贝,请使用以下语法:
for k in range(10):
a[k] = td[:]
演示:
>>> d = {}
>>> el = [1, 2, 3]
>>> d[0] = el
>>> d[1] = el
>>> map(id, d.values())
[28358416, 28358416]
关于python - 更改一个字典值会更改所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13498453/