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)

结果正确:

相关推荐
家的尚尚签1 小时前
高定木作企业实践:案例分享与成果展示
大数据·人工智能·python
haosend2 小时前
极简小白Python教程-实现能基本看懂和简单编写代码
python·路由器·交换机·网络自动化
码农小韩2 小时前
AIAgent应用开发——大模型理论基础与应用(六)
人工智能·python·提示词工程·aiagent·deepseek
一株菌子2 小时前
10.12 总结
开发语言·python
敏编程2 小时前
一天一个Python库:pyjwt - 安全地编码和解码JWT
python
长安牧笛2 小时前
让车学会耍赖式安全停车,危险时优先靠边停车,不是硬刹,颠覆紧急制动逻辑,输出平稳停车。
python·编程语言
Loo国昌2 小时前
【AI应用开发实战】05_GraphRAG:知识图谱增强检索实战
人工智能·后端·python·语言模型·自然语言处理·金融·知识图谱
一个处女座的程序猿O(∩_∩)O2 小时前
Python面向对象的封装特性详解
开发语言·python
zhaoyin19942 小时前
python基础
开发语言·python
geovindu3 小时前
python: Template Method Pattern
开发语言·python·设计模式·模板方法模式