Python: 全局命名空间中的列表通过函数无意中被修改

Python: List in global namespace gets unintentionally modified through function

我在 Python 中可能遇到了一个非常基本的问题。但是,如果有人能帮助我理解这里发生的事情,我将非常感激:

我的代码如下:

purchaseprices = {'Stock_A': [[10, 4.21],[20, 5.23], [5, 8.32]],
                  'Stock_B': [[5, 8.23],[15, 7.42], [10, 7.53]]}



def update_purchaseprices(name, number_of_shares):
    remaining_number_of_shares = number_of_shares
    updated_purchaseprices = purchaseprices[name][:]
    indices_to_delete = []
    for i in range(len(updated_purchaseprices)):
        if updated_purchaseprices[i][0] < remaining_number_of_shares:
            remaining_number_of_shares -= updated_purchaseprices[i][0]
            indices_to_delete.append(i)
        else:
            updated_purchaseprices[i][0] = updated_purchaseprices[i][0] - remaining_number_of_shares
            break
    updated_purchaseprices = [i for j, i in enumerate(updated_purchaseprices) if j not in indices_to_delete]
    return updated_purchaseprices

name = "Stock_A"
number_of_shares = 34

print(purchaseprices['Stock_A'])
updated_purchaseprices = update_purchaseprices(name, number_of_shares)
print(updated_purchaseprices) # this works as expected
print(purchaseprices['Stock_A']) # why did the original list got changed as well?

这是我想要做的:我有一个原始列表,它存储在一个名为 purchaseprices 的字典中。此列表可以通过 purchaseprices['Stock_A’] 访问。现在我试着写一个函数到 return 一个名为 updated_purchaseprices 的列表,它基本上是原始列表的修改版本。为了保持原始列表不变,我通过包含 updated_purchaseprices = purchaseprices[name]: 制作了一份副本。不幸的是,我的代码仍然更改了原始列表。有人可以告诉我为什么会这样吗?

您可能知道,因为您使用了 [:],列表是可变的,您需要在函数中复制一份。但是副本仍然包含原始对象(子列表)。

你也需要复制这些!

替换:

updated_purchaseprices = purchaseprices[name][:]

与:

updated_purchaseprices = [l.copy() for l in purchaseprices[name]]

或:

import copy
updated_purchaseprices = copy.deepcopy(purchaseprices[name])