12 python 初学(深浅拷贝、集合)

深浅拷贝:参考:http://www.cnblogs.com/yuanchenqi/articles/5782764.html

s = [[1, 2], 'lily', 'hello']
s2 = s.copy()
print(s2)
s2[0][1] = 3
print(s2)
print(s)
# >>> [[1, 2], 'lily', 'hello']
# >>> [[1, 3], 'lily', 'hello']
# >>> [[1, 3], 'lily', 'hello']
# 输出结果显示当改变列表内的元素的时候,两个会一起改变

s2 = s s2 = s.copy 是不一样的。

s2 = s:是将 s 整体的一个内存地址直接复制给了 s2,相当于 s2 s 的一个别名,两个都指向同一块内存空间

s2 = s.copy:是将s 内的每一份地址都拷贝了一份给 s2

浅拷贝:只拷贝一层,不拷贝第二层

深拷贝:克隆一份,和原来完全没关系  s2 = copy.deepcopy(s)

猜你喜欢

转载自www.cnblogs.com/mlllily/p/10242267.html