有时,需要重用任何对象,因此复制方法总是很有用的。 Python用其语言提供了多种方法来实现这一目标。这篇特定的文章旨在演示列表中存在的复制方法。由于列表被广泛使用,因此它的副本也是必需的。
语法:list.copy()参数:无返回:返回列表的浅拷贝。浅拷贝意味着新列表中的任何修改都不会反映到原始列表中
代码1:演示list.copy()的工作
# 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))
输出:
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]
深拷贝与浅拷贝: 一个分析
深层复制意味着,如果我们修改任何列表,更改都将在两个列表中反映出来,因为它们指向同一参考。而在浅表复制中,当我们在任何列表中添加元素时,只有该列表会被修改。
深层复制技术:
- 使用copy.deepcopy()
- 使用“=”运算符
浅拷贝技术:
- 使用copy.copy()
- 使用清单.copy()
- 使用切片
代码2:演示浅层和深层复制技术
# Python 3 code to demonstrate
# techniques of deep and shallow copy
import copy
# Initializing list
lis1 = [ 1, 2, 3, 4 ]
# Using shallow copy techniques to create a shallow copy
lis2 = lis1.copy()
lis3 = copy.copy(lis1)
lis4 = lis1[:]
# Adding new element to new lists
lis2.append(5)
lis3.append(5)
lis4.append(5)
# Printing lists after adding new element
# No change in old list
print ("The new list created using copy.copy():" + str(lis2))
print ("The new list created using list.copy():" + str(lis3))
print ("The new list created using slicing:" + str(lis4))
print ("The old list after adding new element to new list :" + str(lis1))
print ("\n")
# Using deep copy techniques to create a deep copy
lis2 = lis1
lis3 = copy.deepcopy(lis1)
# Adding new element to new lists
lis2.append(5)
lis3.append(5)
# Printing lists after adding new element
# changes reflected in old list
print ("The new list created using copy.deepcopy():" + str(lis2))
print ("The new list created using =:" + str(lis3))
print ("The old list after adding new element to new list :" + str(lis1))
输出:
The new list created using copy.copy():[1, 2, 3, 4, 5] The new list created using list.copy():[1, 2, 3, 4, 5] The new list created using slicing:[1, 2, 3, 4, 5] The old list after adding new element to new list :[1, 2, 3, 4] The new list created using copy.deepcopy():[1, 2, 3, 4, 5] The new list created using =:[1, 2, 3, 4, 5] The old list after adding new element to new list :[1, 2, 3, 4, 5]
相关用法
- Python PIL copy()用法及代码示例
- Python shutil.copy()用法及代码示例
- Python set copy()用法及代码示例
- Python Dictionary copy()用法及代码示例
- Python Numpy matrix.copy()用法及代码示例
- Python Pandas TimedeltaIndex.copy用法及代码示例
- Python numpy.ndarray.copy()用法及代码示例
- Python Pandas Index.copy()用法及代码示例
注:本文由纯净天空筛选整理自manjeet_04大神的英文原创作品 Python list | copy() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。