寶可夢的組合
小智是一位寶可夢訓練家,他遇到了一組共 5 隻的寶可夢。這些寶可夢已經載入到你這個工作階段的清單(名稱為 pokemon)中,並為方便起見列印在主控台。
小智想嘗試捕捉其中幾隻,但他的圖鑑一次只能儲存兩隻寶可夢。我們來用 itertools 模組中的 combinations,看看小智可以捕捉的所有寶可夢配對有哪些。
本練習屬於課程
撰寫高效的 Python 程式碼
練習說明
- 從
itertools匯入combinations。 - 建立一個名為
combos_obj的「combinations 物件」,其中包含pokemon清單中所有可能的寶可夢配對。每個配對包含2隻寶可夢。 - 將
combos_obj解包成名為combos_2的清單。 - 小智已經升級他的圖鑑,現在可以儲存四隻寶可夢。使用
combinations收集所有由4隻不同寶可夢所組成的組合。使用星號(*)將這些組合直接存成名為combos_4的清單。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import combinations from itertools
____ ____ ____ ____
# Create a combination object with pairs of Pokémon
combos_obj = ____(____, ____)
print(type(combos_obj), '\n')
# Convert combos_obj to a list by unpacking
combos_2 = ____
print(combos_2, '\n')
# Collect all possible combinations of 4 Pokémon directly into a list
combos_4 = ____
print(combos_4)