2010-07-04 20 views
1

我之前已經問過這個問題了,但是修正不適用於x = [[]],我猜是因爲它是一個嵌套列表,這是我將要處理的內容。如何阻止Python函數修改其輸入?

def myfunc(w): 
y = w[:] 
y[0].append('What do I need to do to get this to work here?') 
y[0].append('When I search for the manual, I get pointed to python.org, but I can\'t find the answer there.') 
return y 

x = [[]] 
z = myfunc(x) 
print(x) 
+1

請參閱http://stackoverflow.com/questions/2541865 – jweyrich 2010-07-04 06:06:32

+0

重複:http://stackoverflow.com/questions/845110/emulating-pass-by-value-behaviour-in-python – ChristopheD 2010-07-04 06:18:08

回答

3

這裏是你如何能解決你的問題:

def myfunc(w): 
    y = [el[:] for el in w] 
    y[0].append('What do I need to do to get this to work here?') 
    y[0].append('When I search for the manual, I get pointed to python.org, but I can\'t find the answer there.') 
    return y 

x = [[]] 
z = myfunc(x) 
print(x) 

的事兒[:]是,它是一個淺拷貝。您還可以從copy模塊導入深度複製以獲得正確的結果。

1

使用copy module並使用deepcopy函數創建輸入的深層副本。修改副本而不是原始輸入。

import copy 

def myfunc(w): 
    y = copy.deepcopy(w) 
    y[0].append('What do I need to do to get this to work here?') 
    y[0].append('When I search for the manual, I get pointed to python.org, but I can\'t find the answer there.') 
    return y 
x = [[]] 
z = myfunc(x) 
print(x) 

在使用此方法之前,請先閱讀deepcopy(檢查上述鏈接)的問題並確保它是安全的。