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)

结果正确:

相关推荐
安全系统学习15 分钟前
网络安全之框架安全漏洞分析
开发语言·python·计算机网络·web安全·网络安全
天天爱吃肉821826 分钟前
【新能源汽车技术全景解析:构建智能出行新生态】
python·汽车
loveCode30 分钟前
基于Python实现一个 Windows Tree 命令工具
python
扑克中的黑桃A1 小时前
Python:类方法、实例方法与静态方法深度解析(补)
python
Lanqing_07601 小时前
京东开放平台获取京东商品详情API接口操作解答
java·前端·python·api·电商·电商数据
Lenyiin1 小时前
第 87 场周赛:比较含退格的字符串、数组中的最长山脉、一手顺子、访问所有节点的最短路径
java·c++·python·leetcode·周赛·lenyiin
User_芊芊君子1 小时前
Java异步编程:提升性能的实战秘籍
java·开发语言·python
烧烤店小蚂蚁1 小时前
打卡day52
python·深度学习
山花2 小时前
什么是“Pythonic”?——写出更优雅的Python代码(下)
后端·python
蓝婷儿2 小时前
Python 爬虫入门 Day 1 - 网络请求与网页结构基础
开发语言·python·学习