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)

结果正确:

相关推荐
秋刀鱼 ..2 分钟前
2026年电力电子与电能变换国际学术会议 (ICPEPC 2026)
大数据·python·计算机网络·数学建模·制造
znhy_2312 分钟前
day35打卡
python
盼哥PyAI实验室26 分钟前
12306反反爬虫策略:Python网络请求优化实战
网络·爬虫·python
deephub33 分钟前
DeepSeek-R1 与 OpenAI o3 的启示:Test-Time Compute 技术不再迷信参数堆叠
人工智能·python·深度学习·大语言模型
力江1 小时前
FastAPI 最佳架构实践,从混乱到优雅的进化之路
python·缓存·架构·单元测试·fastapi·分页·企业
Raink老师1 小时前
第 11 章 错误处理与异常
python
Lululaurel1 小时前
AI编程文本挖掘提示词实战
人工智能·python·机器学习·ai·ai编程·提示词
HappRobot1 小时前
Python 面向对象
开发语言·python
BoBoZz192 小时前
AlignTwoPolyDatas 基于ICP算法的配准和相机视角切换
python·vtk·图形渲染·图形处理
嗝o゚2 小时前
Flutter与开源鸿蒙:一场“应用定义权”的静默战争,与开发者的“范式跃迁”机会
python·flutter