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)

结果正确:

相关推荐
深蓝电商API1 分钟前
爬虫任务调度:APScheduler 定时执行
开发语言·爬虫·python
kang_jin2 分钟前
超详细 Python 爬虫指南
开发语言·爬虫·python
亓才孓9 分钟前
【Stream】讲常见数据结构转为map<String,Long>
数据结构·windows·python
weixin1997010801610 分钟前
网易考拉商品详情页前端性能优化实战
java·前端·python·性能优化
凌晨一点的秃头猪12 分钟前
文件路径中 / 和 \ 的使用规则
python
IT北辰17 分钟前
不规则 Excel“数据提取——教师课表自动汇总实战
开发语言·爬虫·python
Watink Cpper21 分钟前
[项目构建]ubuntu24.04下从零部署limap步骤与问题解决方案
python·conda·三维建模·colmap·ubuntu24.04·三维线重建·limap
进击的雷神22 分钟前
无分页一次性加载、多级CSS类名定位、动态User-Agent轮换、断点本地备份——意大利塑料展爬虫四大技术难关攻克纪实
前端·css·爬虫·python
一灰灰blog24 分钟前
从零掌握 Spring AI Alibaba Skill:定义、注册与渐进式披露
人工智能·python·spring