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)

结果正确:

相关推荐
小鹿的周先生23 分钟前
第11章-Structured-Output
开发语言·人工智能·python
梦在远山后39 分钟前
通过 WSS 让 Server 安全调用 Desktop 本地工具(下01):Ticket、人工确认、幂等与断线对账
python·langchain·agent
泡海椒1 小时前
JQuick-Excel 实战:FORMAT 管理日期与数字的 Excel 显示
开发语言·python·excel
学掌门2 小时前
老司机带你十分钟入门Python!
开发语言·python
YEGE学AI算法3 小时前
Python实现Log-Mel Fbank:分帧、加窗、FFT与Mel滤波器组
python·语音识别·fbank·log-mel·音频特征
甜到心里的蛋糕3 小时前
Playwright 无头浏览器自动发布 CSDN 图文草稿的实践(持久化 profile + 图床直传)
运维·python·playwright·爬虫自动化·博客运营
jason.zeng@15022073 小时前
(六)Prompt 优化
python·ai·langchain·prompt·ai编程·llama
全栈练习生4 小时前
大模型推理全链路
python·ai
泡海椒4 小时前
JQuick-Excel VALIDATION 实战:用作用范围约束 Excel 导入校验
开发语言·python·excel
小静AI工程实验室6 小时前
Python 爬虫解析 JSON-LD:多块 script、@graph 与坏数据的 9 个边界
爬虫·python·json