我在這裏遇到了python的問題。Python:防止參數數組被全局修改
def test(n,myList):
if n>0:
myList.append("Test")
print ("BEFORE CALL Instance ", n, myList)
test(n-1,myList)
print ("AFTER CALL Instance ", n, myList)
else:
return
執行經由test(5,[])
:如果我通過每次被調用時增加了一些對數組的遞歸函數傳遞數組,該數組中的每個實例
代碼改性結果:
BEFORE CALL Instance 5 ['Test']
BEFORE CALL Instance 4 ['Test', 'Test']
BEFORE CALL Instance 3 ['Test', 'Test', 'Test']
BEFORE CALL Instance 2 ['Test', 'Test', 'Test', 'Test']
BEFORE CALL Instance 1 ['Test', 'Test', 'Test', 'Test', 'Test']
AFTER CALL Instance 1 ['Test', 'Test', 'Test', 'Test', 'Test']
AFTER CALL Instance 2 ['Test', 'Test', 'Test', 'Test', 'Test']
AFTER CALL Instance 3 ['Test', 'Test', 'Test', 'Test', 'Test']
AFTER CALL Instance 4 ['Test', 'Test', 'Test', 'Test', 'Test']
AFTER CALL Instance 5 ['Test', 'Test', 'Test', 'Test', 'Test']
實際問題:
每個子函數都在修改所有父函數中的數組。我怎樣才能防止這一點?
複製列表到一個新的,修改它在相同的輸出結果與上述
myListNew=myList
myListNew.append("Test")
+1 - 沒錯,只是改變爲'測試(N-1,myList中[:])' – sberry 2010-01-26 18:52:48
是否有關於陣列(字典)這樣做太一些解決方法嗎?它說「不可能的類型」。 – lamas 2010-01-26 18:54:08
檢出庫中的複製模塊:'another_d = copy.copy(d)'。或者嘗試'another_d = dict(d)'。 – jcdyer 2010-01-26 19:01:06