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)

结果正确:

相关推荐
tottoramen2 分钟前
如何安装龙虾
python
QC·Rex11 分钟前
AI Agent 任务规划实战:从 ReAct 到 Plan-and-Solve 的完整指南
人工智能·python·react
kcuwu.1 小时前
Python面向对象:封装、继承、多态
开发语言·python
YuanDaima20481 小时前
LangChain基础配置与对话模型实战
人工智能·python·langchain·大模型·智能体·langgraph
河西石头1 小时前
分享python项目与开源python项目中的效率法宝--requirements文件的使用
开发语言·python·requirements文件·批量安装python依赖·python虚拟环境配置
不懒不懒1 小时前
【卷积神经网络作业实现人脸的关键点定位功能】
开发语言·python
Bert.Cai1 小时前
Python集合简介
开发语言·python
tryCbest2 小时前
Java和Python开发项目部署简介
java·开发语言·python
ZTLJQ2 小时前
任务调度的艺术:Python分布式任务系统完全解析
开发语言·分布式·python
敏编程2 小时前
一天一个Python库:isodate - 处理 ISO 8601 日期时间格式
python