如何只复制Python列表中的值而不复制引用?

2024-04-19 08:26:22 发布

您现在位置:Python中文网/ 问答频道 /正文

具体来说,我想创建一个列表的备份,然后对该列表进行一些更改,将所有更改附加到第三个列表,然后在进行进一步更改之前用备份重置第一个列表,等等,直到完成更改并想将第三个列表中的所有内容复制回第一个列表。不幸的是,似乎每当我在另一个函数中更改第一个列表时,备份也会更改。使用original = backup效果不太好;使用

def setEqual(restore, backup):
    restore = []
    for number in backup:
        restore.append(number)

解决我的问题;即使我成功地从备份中恢复了列表,但是只要我更改了原始列表,备份就会更改。你知道吗

我该如何着手解决这个问题?你知道吗


Tags: 函数innumber内容列表fordefrestore
2条回答

你想要^{}来做这个。你知道吗

首先要理解的是为什么setEqual方法不能工作:您需要知道how identifiers work。(阅读该链接应该非常有帮助。)对于可能有太多术语的快速分解:在函数中,参数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所说,您可以使用类似于copy函数的功能在当前作用域中重新绑定标识符:

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!

相关问题 更多 >