Python学习笔记:深浅拷贝copy()和deepcopy()

2022-03-09  本文已影响0人  闲酿星河

实例:

import copy

a = ["a", ["b", "c"]]
b = a
d = copy.deepcopy(a)
c = copy.copy(a)
a.append("d")
a[1].append("e")
print(a, b, c, d)

输出内容:

['a', ['b', 'c', 'e'], 'd'] ['a', ['b', 'c', 'e'], 'd'] ['a', ['b', 'c', 'e']] ['a', ['b', 'c']]

其他例子

实例1:

import copy

a = ["a", "b", "c"]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
print(a, b, c, d)
print(id(a), id(b), id(c), id(d))

输出内容:

['a', 'b', 'c'] ['a', 'b', 'c'] ['a', 'b', 'c'] ['a', 'b', 'c']
1952786892928 1952786892928 1952786869760 1952786944768

实例2:

import copy

a = ("a", "b", "c")
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
print(a, b, c, d)
print(id(a), id(b), id(c), id(d))

输出内容:

('a', 'b', 'c') ('a', 'b', 'c') ('a', 'b', 'c') ('a', 'b', 'c')
1436892318272 1436892318272 1436892318272 1436892318272

实例3:

import copy

a = ("a", ["b", "c"])
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
print(a, b, c, d)
print(id(a), id(b), id(c), id(d))

输出内容:

('a', ['b', 'c']) ('a', ['b', 'c']) ('a', ['b', 'c']) ('a', ['b', 'c'])
2377116479296 2377116479296 2377116479296 2377116506368
上一篇下一篇

猜你喜欢

热点阅读