wro*_*ame 0 python backup restore list python-3.x
具体来说,我想创建一个列表的备份,然后对该列表进行一些更改,将所有更改附加到第三个列表,然后在进行进一步更改之前使用备份重置第一个列表等,直到我完成进行更改并希望将第三个列表中的所有内容复制回第一个.不幸的是,似乎每当我对另一个函数中的第一个列表进行更改时,备份也会发生变化.使用original = backup效果不佳; 也没用过
def setEqual(restore, backup):
restore = []
for number in backup:
restore.append(number)
Run Code Online (Sandbox Code Playgroud)
解决我的问题; 即使我从备份中成功恢复了列表,但每当我更改原始列表时,备份仍然会更改.
我该如何解决这个问题?
首先要理解的是,为什么该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.'
Run Code Online (Sandbox Code Playgroud)
所以,在你的功能中,当你说:
restore = []
Run Code Online (Sandbox Code Playgroud)
您实际上是将恢复绑定到您正在创建的新列表对象.因为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
Run Code Online (Sandbox Code Playgroud)
简化一下,您只能绑定当前正在执行的作用域中的标识符 - 您永远不能编写类似的函数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!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |