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)

结果正确:

相关推荐
SCBAiotAigc11 分钟前
langchain1.2学习笔记(一):安装langchain
人工智能·python·langchain
亓才孓18 分钟前
java中的Math.Radom拓展
开发语言·python·算法
yongche_shi1 小时前
第八十八篇: 设计一个配置中心
python·面试宝典·设计一个配置中心
itwangyang5201 小时前
AIDD药物筛选与设计详细方法
人工智能·python
NiceAsiv1 小时前
VSCode之打开python终端 取消conda activate的powershell弹窗
vscode·python·conda
蔚说2 小时前
is 与 == 的区别 python
python
cnxy1882 小时前
围棋对弈Python程序开发完整指南:步骤3 - 气(Liberties)的计算算法设计
python·算法·深度优先
叶子2024222 小时前
骨架点排序计算
python
AC赳赳老秦2 小时前
行业数据 benchmark 对比:DeepSeek上传数据生成竞品差距分析报告
开发语言·网络·人工智能·python·matplotlib·涛思数据·deepseek
小鸡吃米…2 小时前
带Python的人工智能——深度学习
人工智能·python·深度学习