『Python』python basic tutorial (2)-basic knowledge finishing


Preface

Explain and organize some basic knowledge commonly used in python

『Python』python basic tutorial (1)-basic data structure

1. Deep copy and shallow copy

1.1 Direct assignment

Only the reference is copied, so there is no isolation between the variables before and after. If the original list changes, the copied variables will also change.

1.2 Shallow copy

Using the copy() function, the outermost periphery of the list is copied, while the objects inside the list are still references.

1.3 Deep copy

Using the deepcopy() function, both the inner and outer parts of the list are copied, so the variables before and after are completely isolated instead of references.

# 示例 demo
import copy 
a = [1, 2, ["a","b"]]
b = a		# 直接赋值,变量前后没有隔离
c = copy.copy(a)		# 浅拷贝
d = a[:]				# 相当于浅拷贝,与 c 相同
e = copy.deepcopy(a)	# 深拷贝,前后两个变量完全隔离

a.append(3)
a[2].append("c")

print(a)	# [1, 2, ["a", "b", "c"], 3]
print(b)	# [1, 2, ["a", "b", "c"], 3]
print(c)	# [1, 2, ["a", "b", "c"]]
print(d)	# [1, 2, ["a", "b", "c"]]
print(e)	# [1, 2, ["a","b"]]

Note: I have n't finished it yet, I'm busy, take the time to continue updating fighting...

Guess you like

Origin blog.csdn.net/libo1004/article/details/112310848