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)

结果正确:

相关推荐
weixin_4166679619 分钟前
银河麒麟V10看门狗试验-1
网络·chrome·python
古城小栈1 小时前
Pydantic 从入门到实践全讲解
python
happylifetree1 小时前
Python18:核心语法-数据存储与运算-运算符-算术运算符
python
打工仔折腾 AI1 小时前
从Attention到BERT:双向预训练语言模型到底解决了什么问题
人工智能·后端·python·深度学习·语言模型·bert
迅猛龙办公室1 小时前
实现第一个python程序(HelloWorld)
开发语言·python
拉格朗日(Lagrange)2 小时前
【第2 章】WorkBuddy 从入门到高手
开发语言·python
老歌老听老掉牙3 小时前
斜抛运动问题分析:给定最大高度与墙面位置的轨迹与时间求解
python·斜抛运动
言乐63 小时前
Python自动去除水印
开发语言·python·django·virtualenv·pygame
czq_26867194873 小时前
Python打卡第31天
开发语言·python
invicinble3 小时前
python 编程语言 认识维度
开发语言·数据库·python