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)

结果正确:

相关推荐
电商API&Tina2 分钟前
电商数据采集API接口||合规优先、稳定高效、数据精准
java·javascript·数据库·python·json
玲娜贝儿--努力学习买大鸡腿版14 分钟前
hot 100 刷题记录(1)
数据结构·python·算法
兮℡檬,32 分钟前
答题卡识别判卷
开发语言·python·计算机视觉
阆遤41 分钟前
利用TRAE对nanobot进行安全分析并优化
python·安全·ai·trae·nanobot
雕刻刀1 小时前
ERROR: Failed to build ‘natten‘ when getting requirements to build wheel
开发语言·python
何双新1 小时前
Odoo 技术演进全解析:从 Widget 到 Owl,从 Old API 到声明式 ORM
python
山川行2 小时前
关于《项目C语言》专栏的总结
c语言·开发语言·数据结构·vscode·python·算法·visual studio code
星辰徐哥2 小时前
C语言游戏开发:Pygame、SDL、OpenGL深度解析
c语言·python·pygame
xcLeigh2 小时前
Python入门:Python3基础练习题详解,从入门到熟练的 25 个实例(六)
开发语言·python·教程·python3·练习题
不懒不懒2 小时前
安装python3.9.7和pycharm-community-2022.3.2.exe以及linux
linux·ide·python·pycharm