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)

结果正确:

相关推荐
ZTLJQ6 小时前
序列化的艺术:Python JSON处理完全解析
开发语言·python·json
H5css�海秀6 小时前
今天是自学大模型的第一天(sanjose)
后端·python·node.js·php
阿贵---6 小时前
使用XGBoost赢得Kaggle比赛
jvm·数据库·python
无敌昊哥战神6 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
李昊哲小课8 小时前
第1章-PySide6 基础认知与环境配置
python·pyqt·pyside
2401_894241929 小时前
用Pygame开发你的第一个小游戏
jvm·数据库·python
Zzzz_my10 小时前
正则表达式(RE)
pytorch·python·正则表达式
天天鸭10 小时前
前端仔写了个 AI Agent,才发现大模型只干了 10% 的活
前端·python·ai编程
setmoon21410 小时前
使用Scikit-learn构建你的第一个机器学习模型
jvm·数据库·python
2401_8331977311 小时前
为你的Python脚本添加图形界面(GUI)
jvm·数据库·python