Python Some Tricks

list 的复制

一般来说,有三种方法:

  • 直接使用 = 赋值,这种方式的复制相当于给一个盒子贴上两个不同的标签,因此,如果操作任何一个标签,都会对另外一个标签进行数据同步。
  • 使用 copy() 方法,这种方式属于浅复制(shallow copy),对于一般的字面值,如数字,不管是修改源 list 还是复制之后的 list,都不会影响另一个。但是,如果修改的是列表中的对象(Object),那么,这个修改也会反映到另一个 list 中。
  • 使用 deepcopy() 方法,这种方式属于深复制(deep copy),不管是一般的字面值,还是对象,对一个 list 修改都不会影响到另外一个 list。

按:使用 deepcopy() 需要引入 copy 库。

一些代码示例:

# working of '=' and copy()
list1 = [1, 2, 3, 4]
list2 = list1
list3 = list1.copy()
print('list1 == list2?', list1 == list2)
print('list1 == list3?', list1 == list3)
print('before modified, the data of list1~list3 are as follows')
print('list1 =', list1)
print('list2 =', list2)
print('list3 =', list3)
print("then we modify list1, let's see what will happen in list1~list3")
list1.append(5)
print('list1 =', list1)
print('list2 =', list2)
print('list3 =', list3)

output:

list1 == list2? True
list1 == list3? True
before modified, the data of list1~list3 are as follows
list1 = [1, 2, 3, 4]
list2 = [1, 2, 3, 4]
list3 = [1, 2, 3, 4]
then we modify list1, let's see what will happen in list1~list3
list1 = [1, 2, 3, 4, 5]
list2 = [1, 2, 3, 4, 5]
list3 = [1, 2, 3, 4]
# working of list.copy()

# Initializing list
lis1 = [ 1, 2, 3, 4 ]

# Using copy() to create a shallow copy
lis2 = lis1.copy()

# Printing new list
print ("The new list created is : " + str(lis2))

# Adding new element to new list
lis2.append(5)

# Printing lists after adding new element
# No change in old list
print ("The new list after adding new element : " + str(lis2))
print ("The old list after adding new element to new list : " + str(lis1))

output:

The new list created is : [1, 2, 3, 4]
The new list after adding new element : [1, 2, 3, 4, 5]
The old list after adding new element to new list : [1, 2, 3, 4]
# techniques of deep and shallow copy
import copy

# Initializing list
list1 = [ 1, [2, 3] , 4 ]

# all changes are reflected
list2 = list1

# shallow copy - changes to
# nested list is reflected,
# same as copy.copy(), slicing

list3 = list1.copy()

# deep copy - no change is reflected
list4 = copy.deepcopy(list1)

list1.append(5)
list1[1][1] = 999

print("list 1 after modification:\n", list1)
print("list 2 after modification:\n", list2)
print("list 3 after modification:\n", list3)
print("list 4 after modification:\n", list4)
list 1 after modification:
 [1, [2, 999], 4, 5]
list 2 after modification:
 [1, [2, 999], 4, 5]
list 3 after modification:
 [1, [2, 999], 4]
list 4 after modification:
 [1, [2, 3], 4]

这里其实还有一种方法,即利用切片进行复制:

list2 = list1[:]

Python Some Tricks
http://fanyfull.github.io/2021/12/01/Python-Some-Tricks/
作者
Fany Full
发布于
2021年12月1日
许可协议