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)

结果正确:

相关推荐
lifloveyou5 小时前
table接口结构
python
Warson_L7 小时前
class 扩展
python
前端与小赵8 小时前
Python 数据结构陷阱与复数运算优化:列表、元组、字典成员操作辨析及 NumPy 高效实践
python
天天进步20158 小时前
Python全栈项目--基于深度学习的视频目标跟踪系统
python·深度学习·音视频
天天进步20158 小时前
Python全栈项目--Python自动化运维工具开发
运维·python·自动化
(●—●)橘子……8 小时前
力扣第503场周赛练习理解
python·学习·算法·leetcode·职场和发展·周赛
爱吃羊的老虎9 小时前
【JAVA】python转java:Spring Boot 入门
java·spring boot·python
小桥流水---人工智能9 小时前
【已解决】ImportError: cannot import name ‘AdamW‘ from ‘transformers.optimization‘
python
芝麻开门GEO9 小时前
泰安GEO优化服务,真的能提升效果吗?
人工智能·python
颜酱9 小时前
选读:工业级调用 LangChain:从 Demo 到企业级应用
python