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)

结果正确:

相关推荐
Jinkxs27 分钟前
从语法纠错到项目重构:Python+Copilot 的全流程开发效率提升指南
python·重构·copilot
技术专家28 分钟前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
段一凡-华北理工大学35 分钟前
【大模型+知识图谱+工业智能体技术架构】~系列文章01:快速了解与初学入门!!!
人工智能·python·架构·知识图谱·工业智能体
IT小Qi1 小时前
iperf3网络测试工具
网络·python·测试工具·信息与通信·ip
以神为界1 小时前
Python入门实操:基础语法+爬虫入门+模块使用全指南
开发语言·网络·爬虫·python·安全·web
xcjbqd01 小时前
Python API怎么加Token认证_JWT生成与验证拦截器实现
jvm·数据库·python
io_T_T1 小时前
如何调用google api 进行开发(使用免费版本)
python
广师大-Wzx2 小时前
一篇文章看懂MySQL数据库(下)
java·开发语言·数据结构·数据库·windows·python·mysql
hef2883 小时前
golang如何使用range over func_golang range over func迭代器使用方法
jvm·数据库·python
qq_380619164 小时前
html如何查看windows
jvm·数据库·python