本文介绍了[:]切片仅制作列表的浅表副本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我从此[:]副本中遇到了特殊的错误.

I have experienced peculiar bugs from this [:] copy.

文档[:]仅产生浅拷贝,但看起来:

The docs say [:] makes only a shallow copy but seems:

a = [1,2,3]
id(a)
3071203276L
b=a[:]
id(b)
3071234156L

id(a)不等于id(b);那怎么只是一个浅表副本?

id(a) is not equal to id(b); how is that only a shallow copy?

特殊情况:

import numpy as np
import random
a = np.array([1,2,3])
b=a[:]
random.shuffle(a)

b相应地更改.

推荐答案

这是一个浅表副本,但是在这种情况下更改b不会影响a,因为元素只是数字.如果它们是引用,则a将被更新:

It is a shallow copy, but changing b does not affect a in this case because the elements are just numbers. If they were references then a would be updated:

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

b[1] = 5
print "a: ", a
print "b: ", b
# a: [1, 2, 3]
# b: [1, 5, 3]

vs

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

b[1][0] = 5
print "a: ", a
print "b: ", b
# a:  [[1], [5], [3]]
# b:  [[1], [5], [3]]

这篇关于[:]切片仅制作列表的浅表副本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 07:26