找出集合之間的全部資料與重疊資料
集合(set)有多種方法可用來合併、比較與分析,這些方法都基於數學的集合論。.union() 方法會回傳一個集合,包含你呼叫該方法的集合裡的所有元素,加上作為引數傳入的其他集合中的元素。你也可以透過在某個集合上使用 .intersection() 方法並傳入另一個集合作為引數,來尋找集合中的重疊資料;若沒有任何相符元素,則會回傳空集合。
在本練習中,你要找出雌性與雄性企鵝物種的聯集與交集。為此,工作空間已預先載入兩個集合:female_penguin_species 與 male_penguin_species。
本練習屬於課程
Python 的資料型別
練習說明
- 計算
female_penguin_species與male_penguin_species的聯集,將結果儲存為all_species。 - 列印
all_species中物種的數量。你可以使用len()函式計算all_species中的物種數量。 - 計算
female_penguin_species與male_penguin_species的交集,找出同時出現於兩者的物種,將結果儲存為overlapping_species。 - 列印
overlapping_species中物種的數量。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Find the union: all_species
all_species = ____
# Print the count of names in all_species
print(____)
# Find the intersection: overlapping_species
overlapping_species = ____
# Print the count of species in overlapping_species
print(____)