開始使用免費開始

統計不同類型的飛機

在這個練習中,給你一個字典 aircraft_engines,其中包含多款常見民航機的引擎類型。你想要計算資料集中每種引擎類型各有多少架飛機。請運用你的 Python 控制流程技巧,撰寫一個含有 if/else 的 for 迴圈,對於每一種新的引擎類型,將變數 counts 加上 1

本練習屬於課程

給 MATLAB 使用者的 Python

檢視課程

練習說明

  • 撰寫一個 for 迴圈,走訪 airplane_types 的每個 key:value 配對。
  • 在每次迭代時,印出「The x airplane has y engines.」,其中 x 是飛機名稱,y 是引擎類型。
  • 每次迭代時,將 counts 字典中對應 engine_type 的值加一。
  • 最後,印出「counts」字典

動手互動練習

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

counts = {}
# Loop over the key:value pairs in airplane_types
for airplane, engine_type in ____.items():
    # Print the aircraft name and engine type of each aircraft
    print("The {} airplane has {} engines.".format(____, ____))
    # Increment the values of the engine_type key in the counts dictionary
    if engine_type in counts:
        counts[engine_type] = ____[engine_type] + 1
    else:
        counts[engine_type] = 1

print(____)
編輯並執行程式碼