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)

结果正确:

相关推荐
黑客思维者29 分钟前
突破 Python 多线程限制:GIL 问题的 4 种实战解法
服务器·数据库·python·gil
FY_20182 小时前
Stable Baselines3中调度函数转换器get_schedule_fn 函数
开发语言·人工智能·python·算法
Coder_Boy_2 小时前
【物联网技术】- 基础理论-0001
java·python·物联网·iot
FY_20182 小时前
SubprocVecEnv 原理、详细使用方法
人工智能·python·机器学习
czliutz2 小时前
使用pdfplumber库处理pdf文件获取文本图片作者等信息
python·pdf
Sunhen_Qiletian2 小时前
《Python开发之语言基础》第七集:库--时间库
前端·数据库·python
smile_Iris2 小时前
Day 30 函数定义与参数
开发语言·python
杨航 AI2 小时前
FORCE_VERIFYING_SIGNATURE=false
python
AI弟2 小时前
推荐系统:带你走进推荐之路(二)
人工智能·python·深度学习·面试·推荐算法
不错就是对3 小时前
mmdetection - Linux环境搭建
图像处理·人工智能·python·深度学习·计算机视觉