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 分钟前
空间智能与计算机视觉的本质差异:不止于识别,更是空间决策能力
人工智能·python·计算机视觉
典典分享指南26 分钟前
Windows 自动化踩坑实录
python·intellij-idea·pyqt·emacs·visual studio
工业一体机老司机28 分钟前
Python实现工业一体机OPC-UA通信:从SDK选型到数据采集实战
开发语言·python·单片机
威联通网络存储32 分钟前
TS-h2477AXU-RP 在化工制造数据场景的部署
python·制造
wuyk55532 分钟前
Python 零基础入门第七章:字典 Dict
开发语言·python
2601_9669496535 分钟前
如何判断盘中最新价相对昨日收盘涨跌幅,并实时触发止盈止损条件单:QuantDash Python 实战
开发语言·python·量化策略·量化·quantdash
桃西西呀1 小时前
刷短视频越刷越窄?SVD 奇异值分解,把 10 万条电影评分拆成你的品味特征
python·数学·数据可视化
大模型码小白1 小时前
Spring AI 框架中集成 MCP 的完整指南:从服务端到客户端的全流程实践
大数据·运维·数据库·人工智能·python·sql·spring
青 春 记 忆1 小时前
零基础入门python29:用 pytest 验收完整 Flask 业务流程
python·flask·后端开发
wanglei2007081 小时前
消息队列的协作模式
开发语言·python