脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 解决python给列表里添加字典时被最后一个覆盖的问题

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

2021-05-19 00:14GJHL_likx Python

今天小编就为大家分享一篇解决python给列表里添加字典时被最后一个覆盖的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> 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]都指向同一个对象,实际上是列表在多次添加(引用)同一个字典。

一种解决的办法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
>>> 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给列表里添加字典时被最后一个覆盖的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/weixin_40096730/article/details/81255089

延伸 · 阅读

精彩推荐