比較 Pokédex
兩位寶可夢訓練家 Ash 與 Misty 想要比較他們各自的寶可夢收藏。我們來看看他們有哪些寶可夢是相同的,以及 Ash 有但 Misty 沒有的寶可夢。
Ash 和 Misty 的 Pokédex(他們的寶可夢收藏)已載入到你的工作階段,分別是名為 ash_pokedex 與 misty_pokedex 的列表。為了方便你查看,這兩個列表已經列印到主控台。
本練習屬於課程
撰寫高效的 Python 程式碼
練習說明
- 將兩個列表(
ash_pokedex與misty_pokedex)各自轉成集合,分別命名為ash_set與misty_set。 - 使用集合方法找出 Ash 與 Misty 兩人都擁有的寶可夢。
- 使用集合方法找出只存在於 Ash 的 Pokédex、但不在 Misty 的 Pokédex 裡的寶可夢。
- 使用集合方法找出只屬於 Ash 或 Misty 其中一人 的寶可夢(也就是只存在於其中一個 Pokédex、而非兩者都有的寶可夢)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Convert both lists to sets
ash_set = ____
misty_set = ____
# Find the Pokémon that exist in both sets
both = ____.____(____)
print(both)
# Find the Pokémon that Ash has and Misty does not have
ash_only = ____.____(____)
print(ash_only)
# Find the Pokémon that are in only one set (not both)
unique_to_set = ____.____(____)
print(unique_to_set)