📜  Python列表复制()方法

📅  最后修改于: 2022-05-13 01:54:50.848000             🧑  作者: Mango

Python列表复制()方法

有时,需要重用任何对象,因此复制方法总是非常有用。 Python在其语言中提供了多种方法来实现这一点。这篇特定的文章旨在演示列表中存在的复制方法。由于该列表被广泛使用,因此其副本也是必要的。

示例 1:演示 list.copy() 的工作原理

Python3
# Python 3 code to demonstrate
# 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))


Python3
# Python 3 code to demonstrate
# 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)


输出:

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]

示例 2:演示浅拷贝和深拷贝的技术

Python3

# Python 3 code to demonstrate
# 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]