Tutorial Study Image

Python copy()

Python 中的 copy() 函数有助于复制集合。我们可以说它返回一个浅拷贝,这意味着新集合中的任何更改都不会反映在原始集合中。


set.copy() 
 

copy() 参数

copy() 方法不接受任何参数。

copy() 返回值

有时我们使用 = 运算符来复制集合,区别在于“=”运算符创建对集合的引用,而 copy() 创建一个新集合。

输入 返回值
set(集合) 浅拷贝

Python 中 copy() 方法的示例

示例 1:Python 中 copy() 方法如何用于集合?


alphabet = {'a', 'b', 'c'}
new_set = alphabet .copy()

new_set.add(d)

print('Alphabets : ', alphabet )
print('New Set: ', new_set)
 

输出


Alphabets:  {'a', 'b', 'c'}
New Set :  {'a', 'b', 'c', 'd'}

示例 2:Python 中 copy() 方法如何使用 = 运算符用于集合?


alphabet = {'a', 'b', 'c'}
new_set = alphabet

new_set.add(d)

print('Alphabets : ', alphabet )
print('New Set: ', new_set)
 

输出


Alphabets:  {'a', 'b', 'c'}
New Set :  {'a', 'b', 'c', 'd'}