為什麼要用 dictionary
為了了解 dictionary 為什麼有用,先看看指令碼中定義的兩個清單。countries 包含一些歐洲國家的名稱。capitals 則列出對應的首都名稱。
本練習屬於課程
Python 中級
練習說明
- 在
countries上使用index()方法以找到'germany'的索引。把這個索引存成ind_ger。 - 使用
ind_ger從清單capitals取出德國的首都,並將其印出。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Definition of countries and capital
countries = ['spain', 'france', 'germany', 'norway']
capitals = ['madrid', 'paris', 'berlin', 'oslo']
# Get index of 'germany': ind_ger
# Use ind_ger to print out capital of Germany