解决python给列表里添加字典时被最后一个覆盖的问题
作者:GJHL_likx 时间:2022-08-24 17:18:42
如下所示:
>>> item={} ; items=[] #先声明一个字典和一个列表,字典用来添加到列表里面
>>> item['index']=1 #给字典赋值
>>> items.append(item)
>>> items
[{'index': 1}] #添加到列表里面复合预期
>>> item['index']=2 #现在修改字典
>>> item
{'index': 2} #修改成功
>>> items.append(item) #将修改后的新字典添加到列表
>>> items #按预期应该是[{'index': 1}, {'index': 2}]
[{'index': 2}, {'index': 2}]
#找一下原因:
>>> id(item),id(items[0]),id(items[1])
(3083974692L, 3083974692L, 3083974692L)
可以看到item,items[0],items[1]都指向同一个对象,实际上是列表在多次添加(引用)同一个字典。
一种解决的办法:
>>> items=[]
>>> for i in range(3):
... item={} #每次都重新声明一个新字典
... item['index']=i
... items.append(item)
... id(item)
...
3084185084L
3084183588L
3084218956L
>>> items
[{'index': 0}, {'index': 1}, {'index': 2}]
>>>
来源:https://blog.csdn.net/weixin_40096730/article/details/81255089
标签:python,列表,字典,覆盖
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Go map发生内存泄漏解决方法
2024-05-05 09:29:52
区别div和span、relative和absolute、display和visibility
2009-12-13 12:18:00
Python超简单容易上手的画图工具库(适合新手)
2021-12-06 04:05:23
![](https://img.aspxhome.com/file/2023/9/67809_0s.jpg)
python GUI库图形界面开发之PyQt5表单布局控件QFormLayout详细使用方法与实例
2023-08-11 19:10:44
![](https://img.aspxhome.com/file/2023/1/112781_0s.png)
VUEJS实战之修复错误并且美化时间(2)
2023-07-02 17:01:24
![](https://img.aspxhome.com/file/2023/3/139893_0s.jpg)
OpenCV 表盘指针自动读数的示例代码
2023-12-29 05:46:38
![](https://img.aspxhome.com/file/2023/7/68917_0s.jpg)
php实现在服务器端调整图片大小的方法
2024-05-13 09:25:46
Centos7 下Mysql5.7.19安装教程详解
2024-01-25 08:28:18
Python的进制转换和ASCLL转换你了解吗
2021-09-18 05:33:59
python实现矩阵乘法的方法
2021-02-22 16:22:18
浅谈flask截获所有访问及before/after_request修饰器
2023-08-21 10:05:59
Python操作RabbitMQ服务器实现消息队列的路由功能
2022-06-21 00:50:39
Java通过数据库表生成实体类详细过程
2024-01-23 15:39:06
![](https://img.aspxhome.com/file/2023/4/70324_0s.png)
python 拷贝特定后缀名文件,并保留原始目录结构的实例
2021-08-30 04:17:46
Vue.js开发环境搭建
2024-05-28 15:55:38
![](https://img.aspxhome.com/file/2023/7/123117_0s.png)
javascript实现无缝上下滚动特效
2024-05-11 09:35:08
![](https://img.aspxhome.com/file/2023/5/125955_0s.jpg)
浅析webpack-bundle-analyzer在vue-cli3中的使用
2024-05-28 16:09:50
![](https://img.aspxhome.com/file/2023/3/123073_0s.png)
pygame实现贪吃蛇游戏
2021-09-23 00:29:21
![](https://img.aspxhome.com/file/2023/2/115512_0s.jpg)
解决Python对齐文本字符串问题
2021-08-20 10:22:26
详解go-micro微服务consul配置及注册中心
2024-04-23 09:48:20
![](https://img.aspxhome.com/file/2023/8/134318_0s.jpg)