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)

结果正确:

相关推荐
2301_816660212 小时前
PHP怎么处理Eloquent Attribute Inference属性推断_Laravel从数据自动推导类型【操作】
jvm·数据库·python
第一程序员2 小时前
数据工程 pipelines 实践
python·github
知行合一。。。3 小时前
Python--05--面向对象(属性,方法)
android·开发语言·python
郝学胜-神的一滴3 小时前
深度学习必学:PyTorch 神经网络参数初始化全攻略(原理 + 代码 + 选择指南)
人工智能·pytorch·python·深度学习·神经网络·机器学习
qq_372154233 小时前
Go 中自定义类型与基础类型的显式转换规则详解
jvm·数据库·python
LiAo_1996_Y4 小时前
CSS如何实现文字渐变效果_通过background-clip实现艺术字
jvm·数据库·python
2401_887724504 小时前
CSS如何让表单在手机端友好展示_利用Flexbox实现堆叠排版
jvm·数据库·python
zhangchaoxies4 小时前
Layui轮播图(carousel)怎么设置自动播放间隔
jvm·数据库·python
FreakStudio5 小时前
无硬件学LVGL:基于Web模拟器+MiroPython速通GUI开发—布局与空间管理篇
python·单片机·嵌入式·面向对象·并行计算·电子diy
qq_372906935 小时前
如何在 Vuetify 中可靠捕获 Chip 关闭事件(包括键盘触发)
jvm·数据库·python