Python 集合

集合(Set)

集合是無序和無索引的集合。在 Python 中,集合用花括號編寫。

實例

創建集合:

thisset = {"apple", "banana", "cherry"}
print(thisset)

運行實例

注釋:集合是無序的,因此您無法確定項目的顯示順序。

訪問項目

您無法通過引用索引來訪問 set 中的項目,因為 set 是無序的,項目沒有索引。

但是您可以使用 for 循環遍歷 set 項目,或者使用 in 關鍵字查詢集合中是否存在指定值。

實例

遍歷集合,并打印值:

thisset = {"apple", "banana", "cherry"}
for x in thisset:
  print(x)

運行實例

實例

檢查 set 中是否存在 “banana”:

thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)

運行實例

更改項目

集合一旦創建,您就無法更改項目,但是您可以添加新項目。

添加項目

要將一個項添加到集合,請使用 add() 方法。

要向集合中添加多個項目,請使用 update() 方法。

實例

使用 add() 方法向 set 添加項目:

thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)

運行實例

實例

使用 update() 方法將多個項添加到集合中:

thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)

運行實例

獲取 Set 的長度

要確定集合中有多少項,請使用 len() 方法。

實例

獲取集合中的項目數:

thisset = {"apple", "banana", "cherry"}
print(len(thisset))

運行實例

刪除項目

要刪除集合中的項目,請使用 remove()discard() 方法。

實例

使用 remove() 方法來刪除 “banana”:

thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)

運行實例

注釋:如果要刪除的項目不存在,則 remove() 將引發錯誤。

實例

使用 discard() 方法來刪除 “banana”:

thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)

運行實例

注釋:如果要刪除的項目不存在,則 discard() 不會引發錯誤。

您還可以使用 pop() 方法刪除項目,但此方法將刪除最后一項。請記住,set 是無序的,因此您不會知道被刪除的是什么項目。

pop() 方法的返回值是被刪除的項目。

實例

使用 pop() 方法刪除最后一項:

thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)

運行實例

注釋:集合是無序的,因此在使用 pop() 方法時,您不會知道刪除的是哪個項目。

實例

clear() 方法清空集合:

thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)

運行實例

實例

del 徹底刪除集合:

thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)

運行實例

合并兩個集合

在 Python 中,有幾種方法可以連接兩個或多個集合。

您可以使用 union() 方法返回包含兩個集合中所有項目的新集合,也可以使用 update() 方法將一個集合中的所有項目插入另一個集合中:

實例

union() 方法返回一個新集合,其中包含兩個集合中的所有項目:

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)

運行實例

實例

update() 方法將 set2 中的項目插入 set1 中:

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)

運行實例

注釋:union() 和 update() 都將排除任何重復項。

還有其他方法將兩個集合連接起來,并且僅保留重復項,或者永遠不保留重復項,請查看此頁面底部的集合方法完整列表。

set() 構造函數

也可以使用 set() 構造函數來創建集合。

實例

使用 set() 構造函數來創建集合:

thisset = set(("apple", "banana", "cherry")) # 請留意這個雙括號
print(thisset)

運行實例

Set 方法

Python 擁有一套能夠在集合(set)上使用的內建方法。

方法 描述
add() 向集合添加元素。
clear() 刪除集合中的所有元素。
copy() 返回集合的副本。
difference() 返回包含兩個或更多集合之間差異的集合。
difference_update() 刪除此集合中也包含在另一個指定集合中的項目。
discard() 刪除指定項目。
intersection() 返回為兩個其他集合的交集的集合。
intersection_update() 刪除此集合中不存在于其他指定集合中的項目。
isdisjoint() 返回兩個集合是否有交集。
issubset() 返回另一個集合是否包含此集合。
issuperset() 返回此集合是否包含另一個集合。
pop() 從集合中刪除一個元素。
remove() 刪除指定元素。
symmetric_difference() 返回具有兩組集合的對稱差集的集合。
symmetric_difference_update() 插入此集合和另一個集合的對稱差集。
union() 返回包含集合并集的集合。
update() 用此集合和其他集合的并集來更新集合。