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)

结果正确:

相关推荐
Eward-an1 分钟前
LeetCode 1980 题通关指南|3种解法拆解“找唯一未出现二进制串”问题,附Python最优解实现
python·算法·leetcode
梦白.29 分钟前
Python的容器类型
运维·python
@HNUSTer2 小时前
基于 Visual Studio Code 配置 Python 开发环境详细教程
ide·vscode·python·csdn开发云
tuotali20262 小时前
天然气压缩机技术2026,高可靠性长周期运行与智能运维融合路径
运维·python
Ama_tor3 小时前
Flask零基础进阶(中)
后端·python·flask
love530love3 小时前
Windows 11 源码编译 vLLM 0.16 完全指南(RTX 3090 / CUDA 12.8 / PyTorch 2.7.1)
人工智能·pytorch·windows·python·深度学习·vllm·vs 2022
进击的小头3 小时前
第3篇:最优控制理论数学基础——矩阵与向量的导数
python·线性代数·机器学习·矩阵
浩瀚之水_csdn3 小时前
Flask 深度解析:从微内核到企业级架构
python·架构·flask
Calm5503 小时前
Python 编程入门实训 - 知识点总结
python
全栈开发圈3 小时前
新书速览|Seaborn科技绘图:基于Matplotlib的Python数据可视化
python·科技·matplotlib