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)

结果正确:

相关推荐
学无止境小袁同学2 小时前
Google ADK 学习指南
python·llm·agent·多agent·google adk·llmagent·agent cli
郝学胜-神的一滴2 小时前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
LK_073 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
wuyk5553 小时前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel
用户54817845909504 小时前
Java 与 Python 在大模型与智能体领域的选型
java·python
yiangL_4 小时前
1、Python 输入输出实验|print 与 input 人机交互实践
开发语言·python·人机交互
高洁015 小时前
世界模型的因果内核:从预测表象到理解机制
人工智能·python·深度学习·transformer·迁移学习
数字融合5 小时前
透明化视频动态三维重建空间数据零核心技术
人工智能·python·virtualenv
AI创界者6 小时前
Python 进阶实战(五十四章):大模型推理网关终极架构——分布式全局前缀 Trie 缓存同步与多网关高可用协同调度
人工智能·python·aigc