Skip to main content
 首页 » 编程设计

python之每个单元格中带有字典的二维数组

2025年05月04日11tuyile006

下面的代码有点问题。我首先创建一个二维数组,我用字典填充它(实际上每个单元格都使用相同的字典)。现在,当我更新一个单元格更改字典中的值时,整个数组中的所有字典都会更改,而不仅仅是 array[0][0]。请看下面的代码:

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 
print array 

我得到以下输出:

[[{'item2': 25, 'item1': 2},  
  {'item2': 25, 'item1': 2}],  
 [{'item2': 25, 'item1': 2},  
  {'item2': 25, 'item1': 2}]] 

当我想要:

[[{'item2': 25, 'item1': 2},  
  {'item2': 25, 'item1': 20}],  
 [{'item2': 25, 'item1': 20},  
  {'item2': 25, 'item1': 20}]] 

有什么建议吗? 注意:我不能使用 numpy。

请您参考如下方法:

Let's explore your issue by a little example:

假设你有一个列表:

a=['something'] 

还有第二个列表,其中包含:

list_1=[a,a,a] 

所以当你这样做的时候:

a[0]="something_else" 

你认为 list_1 的输出是什么?

让我们检查一下:

a=['something'] 
list_1=[a,a,a] 
 
 
a[0]="something_else" 
print(list_1) 

输出:

[['something_else'], ['something_else'], ['something_else']] 

因为在 python 中变量不存储值,变量只是对对象的引用,而对象存储值所以在 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 

因此您可以看到列表中的所有变量都指向同一个字典,所以如果您将任何内容更改为一个,它将影响主字典。

所以当你这样做的时候:

array[0][0]['item1'] =2 

你不仅在修改数组的字典,你实际上也在修改原始字典让我们检查一下:

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_cell = {'item1': [20,34], 'item2': [25,9]} 

你用这个 dict_cell 运行你的代码,你得到了输出:

[[{'item2': [25, 9], 'item1': 2}, {'item2': [25, 9], 'item1': [20, 34]}], [{'item2': [25, 9], 'item1': [20, 34]}, {'item2': [25, 9], 'item1': [20, 34]}]] 

现在让我们尝试更改原始字典值:

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]}]]  

我们修改了 orional 字典,但它改变了数组列表字典中的内容,因为那是字典的浅拷贝。它复制了 dict 但没有复制嵌套列表。

Solution :

使用深拷贝。