![](/img/trans.png)
[英]If two variables point to the same object, why doesn't reassigning one variable affect the other?
[英]Two dictionary variables point to the same object however they affect eachother
我注意到 Python 的一個行為,其中兩個字典相互影響,即使它們是單獨的變量(我猜指向不同的 memory 位置)。 下面是一個用於 PoC 的簡單 python3 腳本:
first_dict = {'hello' : '1', 'oops': '2'}
second_dict = first_dict
#let's delete a value from first_dict
del first_dict['hello']
#output of the second dictionary which is supposed to be unchanged
print(second_dict)
Output 是:
{'oops': '2'}
我該怎么做才能使第二個陣列不受第一個陣列的影響?
這不是奇怪的行為。 您只是將一個新變量分配給相同的 object。列表就是這種情況,我確信 Python 中的其他可迭代對象。但這是解決方法。 使用deepcopy()
確保任何嵌套數據也被復制,因此在 memory 中創建一個全新的 object。
import copy
first_dict = {'hello' : '1', 'oops': '2'}
second_dict = copy.deepcopy(first_dict)
del first_dict['hello']
print(second_dict)
如果我要使用copy.copy()
,則不會復制嵌套值。 例如,試試看它的行為:
import copy
first_dict = {
'hello' : '1',
'oops': {
'nested value': 'eh oh',
},
}
second_dict = copy.copy(first_dict)
del first_dict['hello']
del first_dict['oops']['nested value']
print(second_dict)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.