取得子集

Python SELF TW
等級 9 , 課堂 4
開放

4.1 根據規則取得子集

子集是一個集合,其所有元素都屬於另一個較大的集合。在 Python 中,有幾個內建方法和運算子可用於操作子集。下面我們來說說如何取得子集、如何檢查一個集合是否是另一個集合的子集,以及如何在不同情境中使用這些知識。

使用 for 循環

你可以創建一個空集合,並透過 for 循環添加符合條件的元素。


my_set = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
even_set = set()
            
for x in my_set:
    if x % 2 == 0:
        even_set.add(x)
            
print(even_set)  # 輸出: {2, 4, 6, 8, 10}
        

這是創建子集最簡單和顯而易見的方法。但還有一些更簡潔的方法。

使用函數 filter()

函數filter() 對每個元素應用一個函數,並返回僅當該函數返回 True 的那些元素。結果需要轉換回集合。


my_set = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
even_set = set(filter(lambda x: x % 2 == 0, my_set))
print(even_set)  # 輸出: {2, 4, 6, 8, 10}
        

filter() 函數中使用 lambda 表達式——這是一種簡短的方式來定義例行函數或規則以進行過濾。幾堂課後我會詳細介紹 lambda。

4.2 使用集合生成式

還記得 List Comprehension 嗎?當我們在方括號中指定快速生成列表及其元素的方法?這個語法工具有如下形式:


[表達式 for 變數 in 順序]

其中:

  • 變數 — 某個變數的標識符,
  • 順序 — 該變數接受的值的順序(可以是列表、字符串或通過 range 函數獲得的對象),
  • 表達式 — 取決於生成器中使用的變數的某個表達式,列表的元素將由該表達式填充。

對於集合有類似的函數,但需要使用花括號:


{表達式 for 變數 in 順序}

集合生成器使得能夠基於現有集合,應用篩選條件輕鬆地創建新集合。

這樣可以選取集合中的偶數元素:


my_set = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
even_set = {x for x in my_set if x % 2 == 0} 
print(even_set)  # 輸出: {2, 4, 6, 8, 10} 

這樣可以選取字符串:


my_set = {1, 2, 3, 4, 5, 6, 7, 8, 9, "apple", "banana"}
even_set = {x for x in my_set if type(x) == str}
print(even_set)  # 輸出: {"apple", "banana"}

4.3 檢查元素的存在

可以對集合執行的基本操作之一是 檢查元素是否在集合中。在 Python 中,有幾種方法來檢查集合中是否存在元素。讓我們討論一下各種檢查方法。

使用運算子 in

檢查集合中是否存在元素最常用和方便的方法是使用 運算子 in。這個方法返回 True,如果元素存在於集合中;否則返回 False


my_set = {1, 2, 3, 4, 5}
print(3 in my_set)  # 輸出: True
print(6 in my_set)  # 輸出: False
            

使用運算子 not in

運算子 not in 是運算子 in 的反面,用於檢查元素不在集合中。它返回 True,如果元素不在集合中;否則返回 False


my_set = {1, 2, 3, 4, 5}
print(6 not in my_set)  # 輸出: True
print(3 not in my_set)  # 輸出: False

使用循環

雖然使用循環來檢查元素在集合中的存在不是最有效的方法,但當你在處理更複雜的數據結構或執行額外操作時,它可能是有用的。


my_set = {1, 2, 3, 4, 5}
element = 3
found = False
            
for item in my_set:
    if item == element:
        found = True
        break
            
print(found)  # 輸出: True
        

4.4 檢查集合的嵌套

Python 提供 運算子 <=方法 issubset() 來檢查一個集合是否是另一個集合的子集。

使用運算子 <=

運算子 <= 讓你輕鬆檢查一個集合是否是另一個集合的子集。


set_a = {1, 2, 3}
set_b = {1, 2, 3, 4, 5}
            
print(set_a <= set_b)  # 輸出: True
print(set_b <= set_a)  # 輸出: False
            
        

使用方法 issubset()

方法 issubset() 與運算子 <= 執行相同的功能,如果一個集合的所有元素都包含在另一個集合中則返回 True


set_a = {1, 2, 3}
set_b = {1, 2, 3, 4, 5}
            
print(set_a.issubset(set_b))  # 輸出: True
print(set_b.issubset(set_a))  # 輸出: False
        

檢查超集合

你也可以檢查一個集合是否是另一個集合的超集,使用 運算子 >=方法 issuperset()

使用 運算子 >=


set_a = {1, 2, 3, 4, 5}
set_b = {1, 2, 3}
            
print(set_a >= set_b)  # 輸出: True
print(set_b >= set_a)  # 輸出: False
            
        

使用方法 issuperset()


set_a = {1, 2, 3, 4, 5}
set_b = {1, 2, 3}
            
print(set_a.issuperset(set_b))  # 輸出: True
print(set_b.issuperset(set_a))  # 輸出: False
            
        
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION