Python 中的三种拷贝方式
赋值拷贝
深拷贝
浅拷贝
赋值拷贝
one = [1, 2, 3]
two = one
print(one, two)
two[0] = 0
print(one, two)
one = [[1], [2], [3]]
two = one
print(one, two)
two[0] = [0]
print(one, two)
one = [[1], [2], [3]]
two = one
print(one, two)
two[0][0] = 0
print(one, two)
'''
[1, 2, 3] [1, 2, 3]
[0, 2, 3] [0, 2, 3]
[[1], [2], [3]] [[1], [2], [3]]
[[0], [2], [3]] [[0], [2], [3]]
[[1], [2], [3]] [[1], [2], [3]]
[[0], [2], [3]] [[0], [2], [3]]
'''
深拷贝
import copy
one = [1, 2, 3]
two = copy.deepcopy(one)
print(one, two)
two[0] = 0
print(one, two)
one = [[1], [2], [3]]
two = copy.deepcopy(one)
print(one, two)
two[0] = [0]
print(one, two)
one = [[1], [2], [3]]
two = copy.deepcopy(one)
print(one, two)
two[0][0] = 0
print(one, two)
'''
[1, 2, 3] [1, 2, 3]
[1, 2, 3] [0, 2, 3]
[[1], [2], [3]] [[1], [2], [3]]
[[1], [2], [3]] [[0], [2], [3]]
[[1], [2], [3]] [[1], [2], [3]]
[[1], [2], [3]] [[0], [2], [3]]
'''
浅拷贝
one = [1, 2, 3]
two = one.copy()
print(one, two)
two[0] = 0
print(one, two)
one = [[1], [2], [3]]
two = one.copy()
print(one, two)
two[0] = [0]
print(one, two)
one = [[1], [2], [3]]
two = one.copy()
print(one, two)
two[0][0] = 0
print(one, two)
'''
[1, 2, 3] [1, 2, 3]
[1, 2, 3] [0, 2, 3]
[[1], [2], [3]] [[1], [2], [3]]
[[1], [2], [3]] [[0], [2], [3]]
[[1], [2], [3]] [[1], [2], [3]]
[[0], [2], [3]] [[0], [2], [3]]
'''
import copy
'''
赋值拷贝
'''
print('---赋值拷贝---')
one = [1, 2, 3]
two = one
print(one, two)
two[0] = 0
print(one, two)
one = [[1], [2], [3]]
two = one
print(one, two)
two[0] = [0]
print(one, two)
one = [[1], [2], [3]]
two = one
print(one, two)
two[0][0] = 0
print(one, two)
'''
深拷贝
'''
print('---深拷贝---')
one = [1, 2, 3]
two = copy.deepcopy(one)
print(one, two)
two[0] = 0
print(one, two)
one = [[1], [2], [3]]
two = copy.deepcopy(one)
print(one, two)
two[0] = [0]
print(one, two)
one = [[1], [2], [3]]
two = copy.deepcopy(one)
print(one, two)
two[0][0] = 0
print(one, two)
'''
浅拷贝
'''
print('---浅拷贝---')
one = [1, 2, 3]
two = one.copy()
print(one, two)
two[0] = 0
print(one, two)
one = [[1], [2], [3]]
two = one.copy()
print(one, two)
two[0] = [0]
print(one, two)
one = [[1], [2], [3]]
two = one.copy()
print(one, two)
two[0][0] = 0
print(one, two)
Python 中的三种拷贝方式
赋值拷贝
深拷贝
浅拷贝
赋值拷贝
one = [1, 2, 3]