Let's explore your issue by a little example:
所以假设你有一个列表:a=['something']
还有第二个列表包含:
^{pr2}$
所以当你这么做的时候:
^{3}$
你认为list_1的输出是什么?在
让我们检查一下:a=['something']
list_1=[a,a,a]
a[0]="something_else"
print(list_1)
输出:[['something_else'], ['something_else'], ['something_else']]
因为在python中,变量不存储值,变量只是引用对象,而object存储值,所以在list_1中,所有变量都指向同一个对象:
正在检查:for i in list_1:
print(id(i))
输出:4329477768
4329477768
4329477768
在您的情况下:dict_cell = {'item1': 20, 'item2': 25}
width = 2
height = 2
array = []
for i in range(height):
row=[]
for j in range(width):
row.append(dict_cell)
array.append(row)
array[0][0]['item1'] =2
for item in array:
if isinstance(item,list):
for sub_item in item:
print(id(sub_item))
输出:4302653768
4302653768
4302653768
4302653768
所以你可以看到列表中的所有变量都指向同一个dict,所以如果你将任何内容更改为一个,它将影响主dict
所以当你这么做的时候:array[0][0]['item1'] =2
您不仅修改了数组的dict,实际上也修改了原始dict,让我们检查一下:dict_cell = {'item1': 20, 'item2': 25}
width = 2
height = 2
array = []
print("before modification {}".format(dict_cell))
for i in range(height):
row=[]
for j in range(width):
row.append(dict_cell)
array.append(row)
array[0][0]['item1'] =2
print("after modification {}".format(dict_cell))
输出:before modification {'item1': 20, 'item2': 25}
after modification {'item1': 2, 'item2': 25}Ok i got the issue but what is the solution?
Try deepcopy:from copy import deepcopy
dict_cell = {'item1': 20, 'item2': 25}
width = 2
height = 2
array = []
for i in range(height):
row=[]
for j in range(width):
row.append(deepcopy(dict_cell))
array.append(row)
array[0][0]['item1'] =2
print(array)
输出:[[{'item1': 2, 'item2': 25}, {'item1': 20, 'item2': 25}], [{'item1': 20, 'item2': 25}, {'item1': 20, 'item2': 25}]]why deepcopy why not copy ?
假设你有这样的dict:dict_cell = {'item1': [20,34], 'item2': [25,9]}
用这个dict_单元格运行代码,得到的输出是:[[{'item2': [25, 9], 'item1': 2}, {'item2': [25, 9], 'item1': [20, 34]}], [{'item2': [25, 9], 'item1': [20, 34]}, {'item2': [25, 9], 'item1': [20, 34]}]]
现在让我们尝试更改原始dict值:dict_cell = {'item1': [20,34], 'item2': [25,9]}
width = 2
height = 2
array = []
for i in range(height):
row=[]
for j in range(width):
row.append(dict_cell.copy())
array.append(row)
array[0][0]['item1'] =2
for key,value in dict_cell.items():
value[0]='changed'
print(array,'\n')
输出:[[{'item1': 2, 'item2': ['changed', 9]}, {'item1': ['changed', 34], 'item2': ['changed', 9]}], [{'item1': ['changed', 34], 'item2': ['changed', 9]}, {'item1': ['changed', 34], 'item2': ['changed', 9]}]]
我们修改了原来的dict,但是它改变了数组list的dict中的内容,因为这是dict的浅拷贝,它复制了dict,但没有复制嵌套列表。在Solution :
使用deepcopy。在