我想更改在字典中鍵入的 2D 串列中的值。我的代碼正在改變我字典中的所有值,這不是有意的。
cache_memory = {}
zero_list = ["0"] * 2 ["00"] * 5
empty_lists = []
# append zero_lists to empty_list to make a 2D LIST
for count in range(2):
empty_lists.append(zero_list)
# store 2D lists with keys
for index in range(2):
cache_memory[index] = empty_lists
cache_memory[0][0][0] = "1"
print(cache_memory)
輸出是:
{0: [['1', '0', '00', '00', '00', '00', '00'], ['1', '0', '00', '00', '00', '00', '00']], 1: [['1', '0', '00', '00', '00', '00', '00'], ['1', '0', '00', '00', '00', '00', '00']]}
我希望它是:
{0: [['1', '0', '00', '00', '00', '00', '00'], ['0', '0', '00', '00', '00', '00', '00']], 1: [['0', '0', '00', '00', '00', '00', '00'], ['0', '0', '00', '00', '00', '00', '00']]}
有沒有辦法在 python 中實作這一點,還是應該嘗試不同的解決方法?
uj5u.com熱心網友回復:
在您的代碼的以下行中
for count in range(2):
empty_lists.append(zero_list)
# store 2D lists with keys
for index in range(2):
cache_memory[index] = empty_lists
您正在創建串列的淺表副本,它只是對串列的參考。在副本中進行更改時,相同的更改會反映在原始串列中。這就是為什么字典“cache_memory”中的所有串列都是同一串列的參考,修改一個串列中的元素會修改所有參考的串列。為了獲得滿意的輸出,您需要創建和存盤串列的深層副本,這可以使用 python 中可用的復制模塊來實作。因此,您需要將代碼修改為:
import copy #importing copy module
cache_memory = {}
zero_list = ["0"] * 2 ["00"] * 5
empty_lists = []
# append zero_lists to empty_list to make a 2D LIST
for count in range(2):
empty_lists.append(copy.deepcopy(zero_list))
# store 2D lists with keys
for index in range(2):
cache_memory[index] = copy.deepcopy(empty_lists)
cache_memory[0][0][0] = "1"
print(cache_memory)
您可以在這篇文章中了解有關淺拷貝和深拷貝的更多資訊Python 中的淺拷貝與深拷貝
uj5u.com熱心網友回復:
當你剛才說cache_memory[index] = empty_lists,Python會采取的cache_memory[index]和empty_lists是一個物件。如果你想設定cache_memory[index]一個復制的empty_lists,那么你可以要么把.copy()后empty_lists在該行或[:]。這兩個都得到了一個副本,empty_lists而不是把它們都當作一個物件。如果您想對此進行更多探索,只需使用以下代碼片段即可。
my_list = [1,2,3]
new_list = my_list
print('Prev my_list:',my_list)
print('Prev new_list:',new_list)
my_list.append(4)
print('New my_list:',my_list)
print('New new_list:',new_list) # As you can see new_list also gets updated
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/376186.html
