我注意到 Python 中有一個奇怪的行為,其中兩個字典相互影響,即使它們是單獨的變數(并且我猜它們指向不同的記憶體位置)。下面是一個簡單的用于 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)
輸出是:
{'oops': '2'}
我該怎么做才能使第二個陣列不受第一個陣列的影響?
uj5u.com熱心網友回復:
這不是奇怪的行為。您只是將一個新變數分配給同一個物件。串列就是這種情況,我確信 Python 中還有其他可迭代物件。但這是解決方法。使用deepcopy()確保任何嵌套資料也被復制,因此在記憶體中創建了一個全新的物件。
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456004.html
標籤:Python python-3.x 字典
下一篇:根據鍵值動態獲取字典
