python - 更改一个字典值会更改所有值

标签 python list dictionary

我在 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/

相关文章:

python - Google 安全浏览查找 API 中的请求无效

python - 如何访问稍后实例化的模型以在 Django 中进行计算?

python - 比较python中两个列表中的元素

python - 在 python 中使用嵌套映射和 itemgetter 进行解析

python - 如何在 Python 中正确合并重叠的日期时间范围

python - 如何快速将csv表导出到python字典?

php - MySQL的英文单词数据库?

python - Scikit Learn TfidfVectorizer : How to get top n terms with highest tf-idf score

python - 如何快速将 pandas 数据框拆分为元组列?

c# - C# 中的 Dictionary.Item