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)

结果正确:

相关推荐
郝学胜-神的一滴8 分钟前
Socket实战:从单端聊天到多用户连接的实现秘籍
服务器·开发语言·python·网络协议·pycharm
zzwq.12 分钟前
线程池与进程池:concurrent.futures高效并发
python
Ricardo-Yang28 分钟前
SCNP语义分割边缘logits策略
数据结构·人工智能·python·深度学习·算法
soragui1 小时前
【Python】第 4 章:Python 数据结构实现
数据结构·windows·python
和小潘一起学AI1 小时前
CentOS 7安装Anaconda
开发语言·python
kcuwu.1 小时前
Python 正则表达式从入门到实战
数据库·python·正则表达式
不解不惑1 小时前
langchain qwen3 构建一个简单的对话系统
pytorch·python·langchain
努力努力再努力dyx1 小时前
【无标题】
开发语言·python
I疯子1 小时前
2026-04-07 打卡第 4 天
python
数据知道1 小时前
claw-code 源码分析:Tool Pool 组装——默认策略、过滤、MCP 开关如何影响「可用工具面」?
python·claude code·claw code