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)

结果正确:

相关推荐
Ulyanov1 天前
高保真单脉冲雷达导引头回波生成:Python建模与实践
开发语言·python·仿真·系统设计·单脉冲雷达
Li emily1 天前
成功接入A股实时行情API获取实时市场数据
人工智能·python·金融·fastapi
shehuiyuelaiyuehao1 天前
22Java对象的比较
java·python·算法
张小凡vip1 天前
Python异步编程实战:基于async/await的高并发实现
开发语言·python
zcbk01681 天前
不踩坑!手把手教你在 Mac 上安装 Windows(含分区/虚拟机/驱动解决方案)
python
Dev7z1 天前
滚压表面强化过程中变形诱导位错演化与梯度晶粒细化机理的数值模拟研究
人工智能·python·算法
吴秋霖1 天前
apple游客下单逆向分析
python·算法·逆向分析
feasibility.1 天前
yolo11-seg在ISIC2016医疗数据集训练预测流程(含AOP调loss函数方法)
人工智能·python·yolo·计算机视觉·健康医疗·实例分割·isic2016
L念安dd1 天前
基于 PyTorch 的轻量推荐系统框架
人工智能·pytorch·python
Liue612312311 天前
YOLO11改进策略卷积篇使用C3k2-PPA替换YOLO11中的卷积即插即用简单高效
python