我有以下類,它只是為我創建一個物件字典。然后將創建的字典 , 復制main_dict到新字典second_dic。
import numpy as np
class MainClass:
def __init__(self):
self.main_dict = dict()
def add(self, k, val):
self.main_dict[k]=val
main_obj = MainClass()
for i in range(1,5):
main_obj.add(k=i, val=np.random.randint(1,10))
print(main_obj.main_dict)
{1: 1, 2: 2, 3: 7, 4: 7}
second_dic = main_obj.main_dict.copy()
print(second_dic)
{1: 1, 2: 2, 3: 7, 4: 7}
Python 似乎不支持像 C 這樣的指標。因此,當我更改 my 中的值時second_dic,更改不會反映在我的main_dict. 我想知道為了讓這種情況發生,我有什么選擇。
second_dic[1]=1000
print(second_dic)
{1: 1000, 2: 2, 3: 7, 4: 7}
print(main_obj.main_dict)
{1: 1, 2: 2, 3: 7, 4: 7}
uj5u.com熱心網友回復:
在您上面的代碼中,您所做的更改second_dic不會反映在其中,main_dict因為為什么會這樣?這兩個是兩個完全不同的字典物件。
如果你想要別名(盡管它真的不推薦,因為它會導致難以檢測的錯誤)你必須分配參考(有點像 C 指標):
second_dic = main_obj.main_dict # Now second_dic is a pointer to main_dict, in a way
second_dic[1] = 1000
print(main_obj.main_dict)
{1: 1000, ...}
uj5u.com熱心網友回復:
的地址second_dic和main_dict不同。因此對 所做的更改second_dic不會反映到main_dict。我使用了上面相同的代碼并顯示了它們的地址,正如預期的那樣,它們是不同的。
>>> id(second_dic) # To print the address
1911354287192
>>> id(main_obj.main_dict) # To print the address
1911354286952
如果您需要second_dic指向main_dict. 我們可以這樣做。
>>> main_obj.main_dict
{1: 6, 2: 10, 3: 10, 4: 3}
>>> second_dic = main_obj.main_dict # pointing to the same location
>>> second_dic
{1: 6, 2: 10, 3: 10, 4: 3}
>>> second_dic[1] = 111 #Changes the value
>>> second_dic
{1: 111, 2: 10, 3: 10, 4: 3}
>>> main_obj.main_dict # Value gets reflected.
{1: 111, 2: 10, 3: 10, 4: 3}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/373972.html
上一篇:Python:生成嵌套字典
