slice操作a [:]是哪种复制?

时间:2019-02-27 16:26:55

标签: python

我离开python一段时间,现在正在准备面试。当我回顾一些基本知识时,我发现了这一点:

>>> a = [1,2]
>>> b = a
>>> b.append(3)
>>> a
[1, 2, 3]

>>> a = [1,2]
>>> a[:] = [1,2,3]
>>> a
[1, 2, 3]

>>> a = [1,2]
>>> b = a[:]
>>> b.append(3)   # /a[:].append(3)
>>> a
[1, 2]

据我了解,在第二种情况下,a [:]充当浅表副本,而在第三种情况下,它是深表副本。有人可以在这个基本概念上为我提供帮助吗?

3 个答案:

答案 0 :(得分:4)

,在第二种情况下,作业左侧的表达式About不进行任何复制(浅或深)的a[:]

它只是说您要用a中的值替换a的完整片段

仅在代码段的第3部分中,[1, 2, 3]会生成a[:]的副本。这将是一个副本,而不是一个深副本。但是为了证明a仅产生浅表副本,您必须使用一些可变对象来填充列表a[:]。目前,您只用a值填充了它们。例如,您可以使用内部列表填充列表int

a

输出:

a = [ ['a', 'b'], 2] # First element of a is a list, which is a mutable object.
b = a[:]             # b will now have a shallow copy of a, which means that
                     # the first element of a and the first element of b, both refer to
                     # the same object, which is the inner list ['a', 'b']
b[0].append('c')     # Mutate the first element of b.
a                    # You'll find that the change is visible thru list a also.

答案 1 :(得分:1)

这是一个浅表副本。但是我认为您误解了“浅”的含义。您的第三个示例仅说明ab是不同的对象。但是,它们包含的项目不是不同的对象。在这种情况下,您看不到它,因为您有数字,但它们始终是不可变的。

但是,如果a中的项目是可变对象(例如,其他列表),则在a中对其进行修改也会在b中对其进行修改< / p>

a = [[]]
b = a[:]
b.append(3) # this does not change a
a[0].append(1) # this changes b
print(b)

答案 2 :(得分:0)

a=[1,2]
b=a         #in this case whatever changes we apply to a or b 
             is reflected in both.
a.append(3)
b
[1, 2, 3]
a
[1, 2, 3]
b.append(4)
a
[1, 2, 3, 4]
b
[1, 2, 3, 4]
a=[[]]
b=a[:]      #in this case whatever changes we apply to
            b is reflected only in b and whatever changes are 
            applied in a is only reflected in a.
 b.append(3)
 a[0].append(1)
 print(b)
 [[1], 3]
 a
 [[1]]
 a=[1,2]
 b=a[:]
 b.append(3)
 b
 [1, 2, 3]                #change only in b.
 a
 [1, 2]                   #no change in a
 a.append(4)   
 a
 [1, 2, 4]                #change only in a.
 b
 [1, 2, 3]                #no change in b.