開始使用免費開始

使用 enumerate

你對疊代器的掌握越來越上手了,做得很好!

你剛從上一支影片學到幾個關於疊代器的新概念,其中之一是 enumerate() 函式。回想一下,enumerate() 會回傳一個 enumerate 物件,它會產生一連串的 tuple,每個 tuple 由一組「索引-值」配對組成。

在這個練習中,給你一個字串清單 mutants。你會用 enumerate() 來練習:先列印出由 tuple 組成的清單,接著在 for 迴圈中把這些 tuple 拆解。

本練習屬於課程

Python 工具箱

檢視課程

練習說明

  • mutants 建立一個由 tuple 組成的清單,並將結果指定給 mutant_list。請務必使用 enumerate() 產生這些 tuple,並用 list() 將其結果轉成清單。
  • 完成第一個 for 迴圈:將對 mutants 呼叫 enumerate() 所產生的 tuple 拆解。拆解時,索引用 index1,值用 value1
  • 以相同方式完成第二個 for 迴圈,但這次把起始索引改為從 1 開始,方法是將它作為引數傳給 enumerate()start 參數。拆解時,索引用 index2,值用 value2

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Create a list of strings: mutants
mutants = ['charles xavier', 
            'bobby drake', 
            'kurt wagner', 
            'max eisenhardt', 
            'kitty pryde']

# Create a list of tuples: mutant_list
mutant_list = ____

# Print the list of tuples
print(mutant_list)

# Unpack and print the tuple pairs
for ____ in ____:
    print(index1, value1)

# Change the start index
for ____ in ____:
    print(index2, value2)
編輯並執行程式碼