【问题标题】:How do I copy only the values and not the references from a Python list?如何仅复制 Python 列表中的值而不是引用?
【发布时间】:2011-01-28 08:53:38
【问题描述】:

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

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

解决我的问题;即使我成功地从备份中恢复了列表,但每当我更改原始列表时,备份仍然会发生变化。

我将如何解决这个问题?

【问题讨论】:

    标签: python list backup python-3.x restore


    【解决方案1】:

    首先要了解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 所说,您可以使用诸如复制功能之类的东西来重新绑定当前范围内的标识符:

    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!
    

    【讨论】:

      【解决方案2】:

      你想要copy.deepcopy()

      【讨论】:

      • 不要忘记“导入副本”来使用它:)
      猜你喜欢
      • 2017-03-15
      • 2018-01-09
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 2017-09-04
      • 1970-01-01
      相关资源
      最近更新 更多