2017-10-17 49 views
0

我需要一個將列表重置爲其原始狀態的函數,所以爲了做到這一點,我將使用列表的副本作爲實現列表的最直接方式。將創建列表副本的函數

每當我對列表(或列表數量)進行更改時,我希望列出其原始狀態列表。由於列表的數量可以更大,我需要一個可以處理它的函數,而不必每次都重複幾行代碼。

我試圖做一個函數,只是簡單地創建一個列表的副本,因此我可以用它來獲得一個原始列表的副本進一步的改動。 但有件事,我很想念,因爲即時得到錯誤:

list1=[1,2,3] 
list2=['a','b','c'] 
list3=[434,52,43] 

def copy_lists(): 
    list1c=list1[:] 
    list2c=list2[:] 
    list3c=list3[:] 

copy_lists() 
list1c.append('b') 
copy_lists() 
#now list1c should be back to orginal 
print(list1c) 


--------------------------------------------------------------------------- 
--------------------------------------------------------------------------- 
NameError         Traceback (most recent call last) 
<ipython-input-5-95468ead1e78> in <module>() 
     9 
    10 copy_lists() 
---> 11 list1c.append('b') 
    12 copy_lists() 

NameError: name 'list1c' is not defined 
+0

'list1c'是一個局部變量,只在'copy_lists'內定義。 –

+1

深度拷貝可能會爲您做到這一點:https://docs.python.org/3.6/library/copy.html –

+0

不要(嘗試)使用如此多的全局變量。以列表形式作爲參數進行復制,然後將這些副本返回到一個元組(或另一個列表)中。 – chepner

回答

1

在Python有可能使對象的副本時要非常小心。如果你做list1c = list1list1c.append('a') list1也會附加'a'。 Here是一篇文章,談論變量何時是指針與另一個變量的實際數據副本。

確保修改對象副本的最佳方法是不會更改原件,即使用複製模塊中的deepcopy function

from copy import deepcopy 
list1 = [1, 2, 3] 
list2 = ['a', 'b', 'c'] 
list3 = [434, 52, 43] 

list1c = deepcopy(list1) 
list2c = deepcopy(list2) 
list3c = deepcopy(list3) 
list1c.append('a') 

print(list1c) 

# list1 will not be modified if you change list1c 
print(list1) 

您現在運行的錯誤是一個範圍問題。當您嘗試使用copy_lists()函數之外的list1c時,您試圖訪問其範圍外的局部變量(在本例中爲copy_lists函數)。 Here is some reading about scoping in python.

如果您想在函數中進行復制,可以通過從copy_lists()函數返回一個元組來完成。

from copy import deepcopy 

list1 = [1, 2, 3] 
list2 = ['a', 'b', 'c'] 
list3 = [434, 52, 43] 


# changed list1 to l1 to avoid having a variable in the inner scope shadow the outer scope 
def copy_function(l1, l2, l3): 
    l1c = deepcopy(l1) 
    l2c = deepcopy(l2) 
    l3c = deepcopy(l3) 
    return l1c, l2c, l3c 


list1c, list2c, list3c = copy_function(list1, list2, list3) 
list1c.append('a') 

print(list1c) 

# list1 will not be modified if you change list1c 
print(list1)