Python 的三种拷贝方式

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)

发布了147 篇原创文章 · 获赞 72 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Pranuts_/article/details/104792424