Python 中的 copy() 函数有助于复制集合。我们可以说它返回一个浅拷贝,这意味着新集合中的任何更改都不会反映在原始集合中。
set.copy()
copy() 方法不接受任何参数。
有时我们使用 = 运算符来复制集合,区别在于“=”运算符创建对集合的引用,而 copy() 创建一个新集合。
| 输入 | 返回值 |
|---|---|
| set(集合) | 浅拷贝 |
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'}
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'}