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)

结果正确:

相关推荐
Csvn14 小时前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
cch891814 小时前
Python主流框架全解析
开发语言·python
sg_knight15 小时前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财15 小时前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
张張40815 小时前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_4235339915 小时前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python
Ricky111zzz15 小时前
leetcode学python记录1
python·算法·leetcode·职场和发展
小白学大数据16 小时前
Selenium+Python 爬虫:动态加载头条问答爬取
爬虫·python·selenium
Hui Baby16 小时前
springboot读取配置文件
后端·python·flask
阿Y加油吧16 小时前
回溯法经典难题:N 皇后问题 深度解析 + 二分查找入门(搜索插入位置)
开发语言·python