開始使用免費開始

寶可夢的組合

小智是一位寶可夢訓練家,他遇到了一組共 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)
編輯並執行程式碼