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)

结果正确:

相关推荐
Imm77733 分钟前
中国知名的车膜品牌推荐几家
人工智能·python
tudficdew38 分钟前
实战:用Python分析某电商销售数据
jvm·数据库·python
sjjhd6521 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
2301_821369611 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python
机 _ 长2 小时前
YOLO26 改进 | 基于特征蒸馏 | 知识蒸馏 (Response & Feature-based Distillation)
python·深度学习·机器学习
2401_832131952 小时前
Python单元测试(unittest)实战指南
jvm·数据库·python
vx_BS813303 小时前
【直接可用源码免费送】计算机毕业设计精选项目03574基于Python的网上商城管理系统设计与实现:Java/PHP/Python/C#小程序、单片机、成品+文档源码支持定制
java·python·课程设计
gzxx2007sddx3 小时前
windows vnpy运行过程及问题记录
python·量化·vnpy
算法_小学生4 小时前
LeetCode 热题 100(分享最简单易懂的Python代码!)
python·算法·leetcode
230万光年的思念4 小时前
【无标题】
python