解决python给列表里添加字典时被最后一个覆盖的问题

yipeiwu_com6年前Python基础

如下所示:

>>> 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}]
>>>

以上这篇解决python给列表里添加字典时被最后一个覆盖的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

两个使用Python脚本操作文件的小示例分享

1这是一个创建一个文件,并在控制台写入行到新建的文件中. #!/usr/bin/env python 'makeTextFile.py -- create text file'...

pybind11在Windows下的使用教程

pybind11在Windows下的使用教程

Pybind11算是目前最方便的Python调用C++的工具了, 介绍一下在vs2019上写Python的扩展的HelloWorld 1. 去下载pybind11  ...

python pygame实现挡板弹球游戏

python pygame实现挡板弹球游戏

学了一天pygame,用python和pygame写一个简单的挡板弹球游戏 GitHub: EasyBaffleBallGame # -*- coding:utf-8 -*- fr...

python中subprocess批量执行linux命令

可以执行shell命令的相关模块和函数有: os.system os.spawn os.popen --废弃 popen --废弃 commands --废弃,3....

Python selenium 三种等待方式详解(必会)

很多人在群里问,这个下拉框定位不到、那个弹出框定位不到…各种定位不到,其实大多数情况下就是两种问题:1 有frame,2 没有加等待。殊不知,你的代码运行速度是什么量级的,而浏览器加载渲...