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)

结果正确:

相关推荐
MediaTea2 小时前
Python:生成器表达式详解
开发语言·python
-To be number.wan3 小时前
Python数据分析:SciPy科学计算
python·学习·数据分析
Dxy12393102163 小时前
DataFrame数据修改:从基础操作到高效实践的完整指南
python·dataframe
overmind4 小时前
oeasy Python 115 列表弹栈用pop删除指定索引
开发语言·python
hnxaoli5 小时前
win10程序(十六)通达信参数清洗器
开发语言·python·小程序·股票·炒股
电饭叔5 小时前
文本为 “ok”、前景色为白色、背景色为红色,且点击后触发 processOK 回调函数的 tkinter 按钮
开发语言·python
雷电法拉珑6 小时前
财务数据批量采集
linux·前端·python
shangjian0077 小时前
Python基础-With关键字
python
zchxzl8 小时前
亲测2026京津冀可靠广告展会
大数据·人工智能·python
时79 小时前
Python 项目环境隔离配置指南:pyenv + venv 组合使用
python