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)

结果正确:

相关推荐
卷无止境32 分钟前
Python生成器与惰性求值:从yield说起的一场"暂停魔法"
后端·python
卷无止境41 分钟前
从一个装饰器说起:拆解 Python 的 @property
后端·python
农村小镇哥42 分钟前
python操作配置文件ini
开发语言·python
love530love9 小时前
OpenClaw Windows Companion 桌面客户端 连接 LM Studio 完整配置指南
人工智能·windows·python·openclaw
cui_ruicheng11 小时前
Python从入门到实战(十六):多进程编程
开发语言·python
_Jimmy_12 小时前
FastAPI + SQLAlchemy全局事务管理
python·fastapi
用户83562907805112 小时前
如何使用 Python 在 Excel 中添加、编辑和删除超链接
后端·python
AC赳赳老秦14 小时前
企业工商公开信息采集分析:OpenClaw 批量查询企业工商信息,生成企业画像报告
大数据·开发语言·python·自动化·php·deepseek·openclaw
FoldWinCard15 小时前
D6 Python 基础语法 --- 保留关键字
开发语言·python
暮暮祈安15 小时前
Celery 新手入门指南
java·数据库·python·flask·httpx