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)

结果正确:

相关推荐
高洁0113 分钟前
DNN案例一步步构建深层神经网络(二)
人工智能·python·深度学习·算法·机器学习
Insight.19 分钟前
背包问题——01背包、完全背包、多重背包、分组背包(Python)
开发语言·python
Lucky高25 分钟前
Pandas库实践1_预备知识准备
python·pandas
Salt_07281 小时前
DAY 36 官方文档的阅读
python·算法·机器学习·github
k***92161 小时前
Python 科学计算有哪些提高运算速度的技巧
开发语言·python
superman超哥1 小时前
仓颉条件变量深度解析与实践:解锁高效并发同步
开发语言·python·c#·仓颉
长空任鸟飞_阿康1 小时前
LangGraph 技术详解:基于图结构的 AI 工作流与多智能体编排框架
人工智能·python·langchain
love530love2 小时前
ComfyUI 升级 v0.4.0 踩坑记录:解决 TypeError: QM_Queue.task_done() 报错
人工智能·windows·python·comfyui
阿坤带你走近大数据2 小时前
Python基础知识-数据结构篇
开发语言·数据结构·python
小智RE0-走在路上2 小时前
Python学习笔记(7)--集合,字典,数据容器总结
笔记·python·学习