[英]How do I copy only the values and not the references from a Python list?
具體來說,我想創建一個列表的備份,然后對該列表進行一些更改,將所有更改附加到第三個列表,然后在進行進一步更改之前用備份重置第一個列表,依此類推,直到完成進行更改,並希望將第三個列表中的所有內容復制回第一個列表中。 不幸的是,似乎每當我在另一個函數中對第一個列表進行更改時,備份也會被更改。 使用original = backup
效果不佳; 也沒有使用
def setEqual(restore, backup):
restore = []
for number in backup:
restore.append(number)
解決我的問題; 即使我成功地從備份中還原了列表,但是無論何時更改原始列表,備份都將更改。
我將如何解決這個問題?
您要copy.deepcopy()
。
首先要了解的是為什么setEqual
方法不能正常工作:您需要知道標識符如何工作 。 (閱讀該鏈接將非常有幫助。)對於可能使用過多術語的快速總結:在函數中,參數restore
綁定到對象,並且您僅使用=
運算符重新綁定該標識符。 這是將標識符restore
綁定到事物的一些示例。
# Bind the identifier `restore` to the number object 1.
restore = 1
# Bind the identifier `restore` to the string object 'Some string.'
# The original object that `restore` was bound to is unaffected.
restore = 'Some string.'
因此,在您的函數中,當您說:
restore = []
您實際上是將還原綁定到正在創建的新列表對象。 由於Python具有本地函數作用域,因此在您的示例中, restore
是將本地函數標識符restore
綁定到新列表。 這不會更改您要傳遞給setEqual
作為還原的任何內容。 例如,
test_variable = 1
setEqual(test_variable, [1, 2, 3, 4])
# Passes, because the identifier test_variable
# CAN'T be rebound within this scope from setEqual.
assert test_variable == 1
簡化一點,您只能在當前正在執行的作用域中綁定標識符,而永遠不能編寫像def set_foo_to_bar(foo, bar)
這樣的函數來影響該函數之外的作用域。 正如@Ignacio所說,您可以使用諸如復制功能之類的方法在當前范圍內重新綁定標識符:
original = [1, 2, 3, 4]
backup = list(original) # Make a shallow copy of the original.
backup.remove(3)
assert original == [1, 2, 3, 4] # It's okay!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.