python二维数组创建赋值问题:更改单个值却更改了所有项的值

python 复制代码
test_list = []
dic1 = {}
test_list = [dic1 for _ in range(3)]
ll = [1, 2, 3]

for i in range(3):
    test_list[i]['value'] = ll[i]

print(test_list)

运行结果:每次赋值都更改了所有项

原因:python的二位数据创建方式就是这样,官方文档中有描述What has happened is that [[]] is a one-element list containing an empty list,

so all three elements of [[]] * 3 are references to this single empty list.

Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:

python 复制代码
>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]

那么,将上述代码修改为:

python 复制代码
test_list = []
test_list = [{} for _ in range(3)]
ll = [1, 2, 3]

for i in range(3):
    test_list[i]['value'] = ll[i]

print(test_list)

结果正确:

相关推荐
胡斌附体6 分钟前
离线docker安装jupyter(python网页版编辑器)
python·docker·jupyter·image·tar·save
java1234_小锋1 小时前
TensorFlow2 Python深度学习 - TensorFlow2框架入门 - 使用Keras实现逻辑回归
python·深度学习·tensorflow·tensorflow2
java1234_小锋1 小时前
TensorFlow2 Python深度学习 - TensorFlow2框架入门 - Sequential顺序模型
python·深度学习·tensorflow·tensorflow2
雨夜的星光6 小时前
Python JSON处理:load/loads/dump/dumps全解析
开发语言·python·json
fen_fen7 小时前
Java打包时,不将本地Jar打包到项目的最终 JAR 中
开发语言·python·pycharm
可触的未来,发芽的智生9 小时前
触摸未来2025.10.10:记忆的种子,当神经网络拥有了临时工作区,小名喜忆记系统
人工智能·python·神经网络·机器学习·架构
mortimer9 小时前
在 Windows 上部署 NVIDIA Parakeet-TDT 遇到的坑
python·github·nvidia
Rock_yzh9 小时前
AI学习日记——卷积神经网络(CNN):完整实现与可视化分析
人工智能·python·深度学习·神经网络·学习·cnn
生信小白菜儿9 小时前
深度学习(DL)概念及实例操作
人工智能·python·深度学习
测试老哥10 小时前
如何编写好测试用例?
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例