a = b和a = b [:]有什么区别? [英] What is the difference between a = b and a = b[:]?

查看:75
本文介绍了a = b和a = b [:]有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是试图了解浅表副本之间的区别.说我有一个清单:

Just trying to understand the difference between shallow copies. Say I have a list:

lst = [1,2,3] 
a = lst
b = lst[:]

有人可以解释一下这些浅拷贝方法之间的区别吗?

Can someone please explain the difference between these shallow copy methods.

推荐答案

a b 之间的区别在于, a 是另一个引用 lst ,但是 b 是对新列表的引用.您可以通过修改 a 来查看.结果是修改了 lst (因为 a lst 指的是同一对象),但 b 却没有修改.

The difference between a and b here is that a is another reference to lst, but b is a reference to a new list. You can see this by modifying a. It results that lst is modified (since a and lst refer to the same object), but b is not modified.

>>> lst = [1,2,3] 
>>> a = lst
>>> b = lst[:]
>>> a
[1, 2, 3]
>>> b
[1, 2, 3]
>>> a[0] = 3
>>> a
[3, 2, 3]
>>> b
[1, 2, 3]
>>> lst
[3, 2, 3]

但是,尽管运算符 [:] 创建了一个副本而不是引用,但是它仍然创建了一个浅副本,这意味着该副本只有一层深.特别是,这意味着,如果列表中的元素是更复杂的对象,则这些对象将不会被复制,而只是对新列表中相同对象的引用.通过尝试使用列表列表进行相同的操作,可以看出这一点:

However, although the operator [:] creates a copy rather than a reference, it still creates a shallow copy, which means that the copy is only one layer deep. In particular, this means that if the elements of the list are more complex objects, those objects will not be copied, but will just be references to the same objects in the new list. This can be seen by trying the same thing with a list of lists:

>>> list2
[[0, 1], [2, 3]]
>>> list3 = list2
>>> list4 = list2[:]
>>> list3
[[0, 1], [2, 3]]
>>> list4
[[0, 1], [2, 3]]
>>> list4[0][0] = 2
>>> list3
[[2, 1], [2, 3]]
>>> list4
[[2, 1], [2, 3]]

请注意,修改列表 list4 的元素的 元素也会修改 list3 .这是因为尽管它们是不同的列表,但是它们的第一个元素都引用相同的列表.

Notice that modifying an element of the element of the list list4 also modifies list3. This is because although they are different lists, their first elements both refer to the same list.

这篇关于a = b和a = b [:]有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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