Python 中的 set copy() 方法


在本教程中,我們將學習關於 **copy** 方法集合資料結構的內容。讓我們詳細瞭解一下。

**copy** 方法用於獲取集合的 **淺複製**。

讓我們看看不同的例子來理解集合的 **普通** 複製和 **淺** 複製。

普通複製

按照以下步驟並理解輸出。

  • 初始化一個集合。
  • 使用賦值運算子將集合賦值給另一個變數。
  • 現在,向複製的集合中新增另一個元素。
  • 列印兩個集合。

你不會發現任何區別。賦值運算子返回集合的 **引用**。兩個集合都指向記憶體中的同一個物件。因此,對任何一個集合所做的任何更改都將反映在兩個集合中。

示例

 線上演示

# initialzing the set
number_set = {1, 2, 3, 4, 5}
# assigning the set another variable
number_set_copy = number_set
# changing the first value of number_set_copy
number_set_copy.add(6)
# printin the both sets
print(f"Set One: {number_set}")
print(f"Set Two: {number_set_copy}")

輸出

如果你執行上面的程式碼,你將得到以下結果。

Set One: {1, 2, 3, 4, 5, 6}
Set Two: {1, 2, 3, 4, 5, 6}

正如我們預期的那樣,當我們更改第二個集合時,第一個集合也發生了更改。如何避免這種情況?

我們可以使用 **淺複製** 來複制集合。有多種方法可以對集合進行淺複製。其中一種方法是使用 **集合** 的 copy 方法。

示例

讓我們看看使用 **copy** 方法的示例。

 線上演示

# initialzing the set
number_set = {1, 2, 3, 4, 5}
# shallow copy using copy
number_set_copy = number_set.copy()
# changing the first value of number_set_copy
number_set_copy.add(6)
# printin the both sets
print(f"Set One: {number_set}")
print(f"Set Two: {number_set_copy}")

輸出

如果你執行上面的程式碼,你將得到以下結果。

Set One: {1, 2, 3, 4, 5}
Set Two: {1, 2, 3, 4, 5, 6}

如果你檢視輸出,你不會發現第一個 **集合** 有任何更改。

結論¶

如果你對本教程有任何疑問,請在評論區提出。

更新於:2020年7月11日

225 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告