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)

结果正确:

相关推荐
文言一心1 小时前
LINUX离线升级 Python 至 3.11.9 操作手册
linux·运维·python
诗词在线1 小时前
中国古代诗词名句按主题分类有哪些?(爱国 / 思乡 / 送别)
人工智能·python·分类·数据挖掘
高锰酸钾_1 小时前
机器学习-L1正则化和L2正则化解决过拟合问题
人工智能·python·机器学习
天天睡大觉2 小时前
Python学习11
网络·python·学习
智航GIS2 小时前
11.11 Pandas性能革命:向量化操作与内存优化实战指南
python·pandas
写代码的【黑咖啡】3 小时前
Python中的Selenium:强大的浏览器自动化工具
python·selenium·自动化
抠头专注python环境配置3 小时前
解决Windows安装PythonOCC报错:从“No module named ‘OCC’ ”到一键成功
人工智能·windows·python·3d·cad·pythonocc
华研前沿标杆游学3 小时前
2026年华研就业实践营|走进字节跳动,解锁科技行业职业新航向
python
啊阿狸不会拉杆3 小时前
《数字图像处理》第 4 章 - 频域滤波
开发语言·python·数字信号处理·数字图像处理·频率域滤波