開始使用免費開始

統計中午前與中午後的事件數

在本章中,你會使用 Capital Bikeshare 單車 W20529 在 2017-10-01 到 2017-12-31 之間的所有騎乘紀錄。這個清單已載入為 onebike_datetimes

清單中的每個元素都是一個包含兩個欄位的字典:start 是一個 datetime 物件,代表行程開始時間(單車從停車座移出時);end 是一個 datetime 物件,代表行程結束時間(單車放回停車座時)。

你可以用這個資料集更深入了解這台單車的使用情形。究竟比較多行程是在中午之前開始,還是中午之後開始?

本練習屬於課程

在 Python 處理日期與時間

檢視課程

練習說明

  • for 迴圈中,完成 if 敘述以檢查行程是否在中午之前開始。
  • for 迴圈中,若行程在中午之前開始就遞增 trip_counts['AM'],若在中午之後開始就遞增 trip_counts['PM']

動手互動練習

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

# Create dictionary to hold results
trip_counts = {'AM': 0, 'PM': 0}
  
# Loop over all trips
for trip in onebike_datetimes:
  # Check to see if the trip starts before noon
  if ____['start'].____ < ____:
    # Increment the counter for before noon
    trip_counts[____] += 1
  else:
    # Increment the counter for after noon
    trip_counts[____] += 1
  
print(trip_counts)
編輯並執行程式碼