Python - 列表中的dict的奇怪行为 [英] Python - Strange behavior with dicts in list

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

问题描述



例如我有这个代码:

  n_of_elems = 2 
n_of_dicts = 3

lst = [{foo':[0] * n_of_elems,'bar' 0] * n_of_elems}] * n_of_dicts

print(lst)

第一个 print 语句给我预期的空列表:


[{'foo' :[0,0],'bar':[0,0]},{'foo':[0,0],'bar':[0,0]},{'foo':[0,0] ,'bar':[0,0]}]


但是,如果我开始填写一些元素,像这样的...

  lst [0] ['foo'] [0] = 23 
lst [0] ['bar'] [ - 1] = 42

打印(lst)

...我得到一个相当意想不到的结果...


[{'foo':[23,0] ,'bar':[0,42]},{'foo':[23,0],'bar':[0,42 ]},{'foo':[23,0],'bar':[0,42]}]


而不是预期的:


[{'foo':[23,0],'bar':[0,42]} ,{'foo':[0,0],'bar':[0,0]},{'foo':[0,0],'bar':[0,0]}]


为什么会这样,我该如何解决?这个事情发生在使用python2和python3



提前谢谢你的帮助和知识。

解决方案

这是因为 dict 是一种可变类型。 此帖适用。基本上,如果 sometype 是可变的,请不要使用 [sometype] * n 语法。相反,请执行以下操作:

  lst = [{foo':[0] * n_of_elems,'bar':[0] * n_of_elems} for _ in range(n_of_dicts)] 


I just noticed some strange behavior with dicts in lists while using python.

For example I have this code:

n_of_elems = 2
n_of_dicts = 3

lst = [{'foo': [0] * n_of_elems, 'bar': [0] * n_of_elems}] * n_of_dicts

print(lst)

The first print statement gives me the expected empty list:

[{'foo': [0, 0], 'bar': [0, 0]}, {'foo': [0, 0], 'bar': [0, 0]}, {'foo': [0, 0], 'bar': [0, 0]}]

But if i start to fill some elements with values in the lists within the dicts, like this...

lst[0]['foo'][0] = 23
lst[0]['bar'][-1] = 42

print(lst)

... I get a rather unexpected result ...

[{'foo': [23, 0], 'bar': [0, 42]}, {'foo': [23, 0], 'bar': [0, 42]}, {'foo': [23, 0], 'bar': [0, 42]}]

... instead of the expected:

[{'foo': [23, 0], 'bar': [0, 42]}, {'foo': [0, 0], 'bar': [0, 0]}, {'foo': [0, 0], 'bar': [0, 0]}]

Why is this, and how can I solve this? This happens both using python2 and python3

Thank you in advance for your help and knowledge.

解决方案

This is because a dict is a mutable type. this post applies. Basically, don't use the [sometype]*n syntax if sometype is mutable. Instead, do this:

lst = [{'foo': [0] * n_of_elems, 'bar': [0] * n_of_elems} for _ in range(n_of_dicts)]

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

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