python copy用法_Python list copy()用法及代码示例

有时,需要重用任何对象,因此复制方法总是很有用的。 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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值