统计中午前后发生的事件
在本章中,您将使用 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)