为什么列表副本上的操作也不会修改原始列表中的元素?

时间:2022-09-06 12:00:52

In Python everything should be represented with a pointer. Therefore, I expected the following code to modify the original list a as well, since I thought the list copy would contain all the original pointers contained in a:

在Python中,一切都应该用指针表示。因此,我期望以下代码也可以修改原始列表,因为我认为列表副本将包含以下内容中包含的所有原始指针:

import copy

a = ["a", "a"]

copy = copy.copy(a)
for (count, e) in enumerate(copy):
    copy[count] += "b"

print copy
print a

I expected to see ["ab", "ab"]. Surprisingly, a still contains ["a", "a"] only while copy indeed contains ["ab", "ab"]. Using copy = list(a) doesn’t work either.

我期望看到[“ab”,“ab”]。令人惊讶的是,只有复制确实包含[“ab”,“ab”]时仍然包含[“a”,“a”]。使用copy = list(a)也不起作用。

I thought this result would only happen if I wrote copy = copy.deepcopy(a).

我认为这个结果只有在我写了copy = copy.deepcopy(a)时才会发生。

Where did I get wrong? What is the proper way of acquiring the references to all elements in a list and modifying them in a mirror list? Or is it just not possible in Python?

我哪里弄错了?获取列表中所有元素的引用并在镜像列表中修改它们的正确方法是什么?或者它在Python中是不可能的?

1 个解决方案

#1


1  

You are confused. The entire purpose of using copy.copy is to make a new list with no reference to the old one. If you do want to keep a reference, then don't copy it:

你很困惑。使用copy.copy的整个目的是创建一个没有引用旧列表的新列表。如果您确实想要保留引用,则不要复制它:

a = ["a", "a"]
copy = a

#1


1  

You are confused. The entire purpose of using copy.copy is to make a new list with no reference to the old one. If you do want to keep a reference, then don't copy it:

你很困惑。使用copy.copy的整个目的是创建一个没有引用旧列表的新列表。如果您确实想要保留引用,则不要复制它:

a = ["a", "a"]
copy = a