更改浅表副本中的列表元素 [英] Changing list elements in shallow copy

查看:67
本文介绍了更改浅表副本中的列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于列表浅表副本的问题.

I have one question about list shallow copy.

在两个示例中,我都修改了列表的一个元素,但是在示例1中,列表b发生了变化,而在示例2中,列表d没有发生变化.我很困惑,因为在两个示例中,我都修改了列表的元素.

In both examples, I modified one element of the list, but in example 1, list b changed, while in example 2, list d is not changed. I am confused since in both examples, I modified an element of the list.

有什么区别?

示例1:

a=[1,2,[3,5],4]
b=list(a)
a[1]=0
print(a)   # [1, 0, [3, 5], 4]
print(b)   # [1, 2, [3, 5], 4]

示例2:

c=[1,2,[3,5],4]
d=list(c)
c[2][0]=0
print(c)   # [1, 2, [0, 5], 4]
print(d)   # [1, 2, [0, 5], 4]

推荐答案

浅表副本意味着您将获得一个新列表,但元素相同.因此,两个列表的第一个元素,第二个元素等都相同.

A shallow copy means that you get a new list but the elements are the same. So both lists have the same first element, second element, etc.

如果您从浅表复制列表中添加,删除或替换一个值,则该更改不会反映在原始值中(反之亦然),因为浅表副本创建了一个新列表.但是,如果您 change 任一更改中的一个元素在两个更改中均可见,因为两个列表都引用相同的项目.因此,内部列表实际上是在新列表和旧列表之间共享的,如果您对其进行更改,则该更改在两个列表中都是可见的.

If you add, remove, or replace a value from the shallow copied list that change is not reflected in the original (and vise-versa) because the shallow copy created a new list. However if you change an element in either that change is visible in both because both lists reference the same item. So the inner list is actually shared between both the new list and the old list and if you change it, that change is visible in both.

请注意,在任何一个示例中您实际上都没有更改元素,在第一个示例中您替换了列表的元素,在第二个示例中,您替换了列表中元素的一个元素.

Note that you actually didn't change an element in either example, you replace an element of the list in the first example and in the second example, you replace an element of an element of your list.

我目前经常使用graphviz,所以让我添加一些图像来说明这一点:

I'm currently using graphviz a lot so let me add some images to illustrate this:

浅表副本意味着您将获得一个新列表,但列表中存储的对象是相同的:

The shallow copy means you get a new list but the objects stored in the list are the same:

如果您替换其中任何一个元素,则相应的元素将仅引用一个新项目(您的第一个示例).查看一个列表如何引用两个列表,另一个列表如何引用零:

If you replace an element in any of these the corresponding element will just reference a new item (your first example). See how one list references the two and the other the zero:

对引用项目的更改将更改该项目,而引用该项目的每个对象都将看到更改:

While a change to an referenced item will change that item and every object that references that item will see the change:

这篇关于更改浅表副本中的列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆