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)

结果正确:

相关推荐
Storynone4 小时前
【Day20】LeetCode:39. 组合总和,40. 组合总和II,131. 分割回文串
python·算法·leetcode
小鸡吃米…5 小时前
Python—— 环境搭建
python
io_T_T5 小时前
python 文件管理库 Path 解析(详细&基础)
python
渔阳节度使6 小时前
SpringAI实时监控+观测性
后端·python·flask
铁手飞鹰6 小时前
Visual Studio创建Cmake工程导出DLL,通过Python调用DLL
android·python·visual studio
飞Link7 小时前
告别盲目找Bug:深度解析 TSTD 异常检测中的预测模型(Python 实战版)
开发语言·python·算法·bug
7yewh7 小时前
jetson_yolo_deployment 02_linux_dev_skills
linux·python·嵌入式硬件·yolo·嵌入式
love530love8 小时前
ComfyUI rgthree-comfy Image Comparer 节点无输出问题排查与解决
人工智能·windows·python·comfyui·rgthree-comfy·nodes 2.0·vue 节点
badhope8 小时前
Docker从零开始安装配置全攻略
运维·人工智能·vscode·python·docker·容器·github
用户0332126663679 小时前
使用 Python 复制 Excel 工作表
python