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)

结果正确:

相关推荐
Thomas.Sir18 分钟前
第38课:TensorFlow|可视化工具TensorBoard全用法【日志写入、指标监控、网络可视化】
人工智能·python·tensorflow
SEO_juper28 分钟前
外贸多语言站最隐蔽的流量杀手:hreflang 错了,谷歌把德语页推给美国人(附审计脚本)
开发语言·前端·python·seo·独立站·谷歌优化
Metaphor69241 分钟前
快速合并 Word 文档【Python 指南】
python·word
JAVA老架构AI智能化1 小时前
如何高质量分块
人工智能·python
泡海椒1 小时前
告别反射低效:JQuick-Java ASM动态调用链性能优化实战
java·python·性能优化
2601_956319881 小时前
用示例和练习,把量化规则先练清楚
人工智能·python
满怀冰雪1 小时前
25-迁移学习入门:加载预训练模型并微调
人工智能·python·机器学习·迁移学习·paddle
2601_962284501 小时前
安卓APP UI自动化测试:Python + UiAutomator2 + pytest + pytest-html
python·pytest·uiautomator2·ui自动化测试·安卓app
2601_962078032 小时前
构建RESTful APIs:使用Python和Flask
python·flask·web开发·api设计·构建restfulapis
半亩码田2 小时前
C#转Python第4.5篇:单元测试:pytest vs xUnit/NUnit
python·单元测试·c#