更改字典中的列表会更改所有列表 [英] Changing list in dictionary changes all lists
问题描述
我在这里阅读了这些帖子,确切地解释了我所遇到的问题,但没有一种解决方案有效:
I have read these posts here explaining exactly the problem I am having, but none of the solutions are working:
我具有2D数组的特定形状,需要使用它来初始化字典中的条目.这是我的操作方式:
I have a specific shape of 2D array I need to initialize the entries in a dictionary with. Here is how I have done it:
empty = []
for x in range(2):
empty.append([])
for y in range(2):
empty[x].append(False)
status = {k:[] for k in ["a", "b", "c"]}
status["a"] = list(empty)
status["b"] = list(empty)
status["c"] = list(empty)
print(status)
status["a"][0][0] = True
print(status)
(例如,简化列表的形状)
(Shape of list simplified for example)
此打印:
{'a': [[False, False], [False, False]], 'b': [[False, False], [False, False]], 'c': [[False, False], [False, False]]}
{'a': [[True, False], [False, False]], 'b': [[True, False], [False, False]], 'c': [[True, False], [False, False]]}
如您所见,设置列表值之一会更改所有列表.我不希望这样,我希望它们是具有不同值的单独列表(在一本词典中).
As you can see, setting one of the lists values changes all of the lists. I do not want this, I want them to be separate lists (in one dictionary) with different values.
最初,我认为我已经做了旧的 newlist = oldlist
错误,在该错误中我将newlist设置为与oldlist相同的对象,但是没有.如您在代码中所见,我正在使用 newlist = list(oldlist)
制作单独的列表.我也尝试过 newlist = oldlist [:]
, newlist = oldlist.copy()
等.
Initially, I thought I had done the old newlist = oldlist
blunder where I set newlist to the same object as oldlist, but nope. As you can see in my code, I am making separate lists using newlist = list(oldlist)
. I have also tried newlist = oldlist[:]
, newlist = oldlist.copy()
, etc.
我想念什么?
推荐答案
from copy import deepcopy
empty = []
for x in range(2):
empty.append([])
for y in range(2):
empty[x].append(False)
status = {k:[] for k in ["a", "b", "c"]}
status["a"] = deepcopy(empty)
status["b"] = deepcopy(empty)
status["c"] = deepcopy(empty)
print(status)
status["a"][0][0] = True
print(status)
您与副本关系密切,但实际上需要深拷贝
you were close with the copy, but you actually neeed a deepcopy
这篇关于更改字典中的列表会更改所有列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!