使用 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)