当前位置:网站首页>Example 007: copy data from one list to another list.

Example 007: copy data from one list to another list.

2022-07-05 08:22:00 Lazy smile

example 007:copy

subject : Copy data from one list to another .

  Program analysis :

 We can use the following methods to copy : Direct assignment =、 Indexes [:]、copy()、deepcopy()

The code is as follows :


import copy

a = [1, 2, 3, 4, ['a', 'b']]
b = a  #  assignment 
c = a[:]  #  Shallow copy 
d = copy.copy(a)  #  Shallow copy 
e = copy.deepcopy(a)  #  Deep copy 

a.append(5)
a[4].append('c')

print('a=', a)
print('b=', b)
print('c=', c)
print('d=', d)
print('e=', e)
a= [1, 2, 3, 4, ['a', 'b', 'c'], 5]
b= [1, 2, 3, 4, ['a', 'b', 'c'], 5]
c= [1, 2, 3, 4, ['a', 'b', 'c']]
d= [1, 2, 3, 4, ['a', 'b', 'c']]
e= [1, 2, 3, 4, ['a', 'b']]

 

summary :

"""

Deep copy , Depth of copy : I have opened up a new memory , Copy all the copied contents

         Deep copy of the list is to change the new list no matter how ( Unidimensional or Multidimensional ), The original list remains unchanged .

Shallow copy , The degree of copying is shallow , Only the first address of the original data is copied , Then through the first address of the original data , To get content .

         Shallow copy , For multidimensional lists , Only the first dimension deep copy

"""

原网站

版权声明
本文为[Lazy smile]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050816109676.html