奇怪的行为与python中的字典列表 [英] weird behaviour with list of dictionaries in python

查看:142
本文介绍了奇怪的行为与python中的字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个执行列表操作的简单代码:

 >>> a = [0] * 5 
>>>> a
[0,0,0,0,0]
>>> a [0] = 5
>>>> a
[5,0,0,0,0]
>>>>

现在,没有异常。



现在,我尝试使用一系列词典而不是整数列表:

 >>> a = [{}] * 5 
>>> a
[{},{},{},{},{}]
>>> a [0] ['b'] = 4
>>>> a
[{'b':4},{'b':4},{'b':4},{'b':4},{'b':4}]
>>>

我不明白为什么我的列表中的所有元素都被修改...



任何人都可以告诉我为什么?还有一个解决方法?

解决方案

这不奇怪。



< >

解决方法:

  a = [{} for x in xrange(5) ] 






[...] * 5 创建一个 ... 和一个五个指针到这个 ... 的列表。 p>

0 是一个不可变的整数。您不能修改它,您可以用另一个整数(例如 a [0] = 5 )替换它。然后它是一个不同的整数。



{} 是一个可变字典。您正在修改它: a [0] ['b'] = 4 。它总是相同的字典。


Here is a simple code that performs operations on lists:

>>> a = [0] * 5
>>> a
[0, 0, 0, 0, 0]
>>> a[0] = 5
>>> a
[5, 0, 0, 0, 0]
>>> 

For now, nothing abnormal.

Now, I try to do the same with a list of dictionaries instead of a list of integers:

>>> a = [{}] * 5
>>> a
[{}, {}, {}, {}, {}]
>>> a[0]['b'] = 4
>>> a
[{'b': 4}, {'b': 4}, {'b': 4}, {'b': 4}, {'b': 4}]
>>> 

I don't understand why all elements of my list are modified...

Can anyone tell me why? And also provide a workaround?

解决方案

This is not weird.


Workaround:

a = [{} for i in xrange(5)]


[…] * 5 creates one and a list of five pointers to this .

0 is an immutable integer. You cannot modify it, you can just replace it with another integer (such as a[0] = 5). Then it is a different integer.

{} is a mutable dictionary. You are modifying it: a[0]['b'] = 4. It is always the same dictionary.

这篇关于奇怪的行为与python中的字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆