我目前在我的文件中使用此解决方案,以从 api 调用返回给定路线的最快巴士出发前的分钟数,然后显示它:
soonestDepartureTimeUnix = min(item["departure_time"] for item in tsl105513Route2["itineraries"][0]["schedule_items"])
minutes = int((soonestDepartureTimeUnix - (time.time()))/60)
但是,当分钟值 = 0 时,这对于路人来说就没那么有用了。
就上下文而言,API 调用的响应如下所示:
{
"route_departures": [
{
"global_route_id": "TSL:105513",
"itineraries": [
{
"branch_code": "",
"direction_headsign": "*******",
"direction_id": 1,
"headsign": "******",
"merged_headsign": "******",
"schedule_items": [
{
"departure_time": 1713461520,
"is_cancelled": false,
"is_real_time": false,
"rt_trip_id": "13811798",
"scheduled_departure_time": 1713461520,
"trip_search_key": "TSL:45069396:369:5:15",
"wheelchair_accessible": 1
},
{
"departure_time": 1713463320,
"is_cancelled": false,
"is_real_time": false,
"rt_trip_id": "13811799",
"scheduled_departure_time": 1713463320,
"trip_search_key": "TSL:45069396:369:5:16",
"wheelchair_accessible": 1
},
{
"departure_time": 1713465120,
"is_cancelled": false,
"is_real_time": false,
"rt_trip_id": "13811800",
"scheduled_departure_time": 1713465120,
"trip_search_key": "TSL:45069396:369:5:17",
"wheelchair_accessible": 1
}
]
}
],
"mode_name": "Bus",
"real_time_route_id": "30048",
"route_color": "2a61a0",
"route_long_name": "******",
"route_network_id": "TransLink|Vancouver",
"route_network_name": "TransLink",
"route_short_name": "**8",
"route_text_color": "ffffff",
"route_type": 3,
"sorting_key": "***",
"tts_long_name": "*****",
"tts_short_name": "*** "
}
]
}
我尝试了多种解决方案,包括跳转到数组中的下一项:
if minutes < 1:
soonestDepartureTimeUnix = (item["departure_time"] for item in tsl105513Route2["itineraries"][1]["schedule_items"])
minutes = int((soonestDepartureTimeUnix - (time.time()))/60)
但这返回了“列表项超出范围”错误。
我也尝试过这个:
if minutes < 1:
soonestDepartureTimeUnix = (item["departure_time"] for item in tsl105513Route2["itineraries"][0]["schedule_items"][1])
minutes = int((soonestDepartureTimeUnix - (time.time()))/60)
但是我收到一个错误,说不能在生成器和浮点数之间进行减法运算。
最后我尝试了这个解决方案,用于检索我在文章中找到的第二低的列表项:
if minutes < 1:
soonestDepartureTimeUnix2 = min(item["departure_time"] for item in tsl105513Route2["itineraries"][0]["schedule_items"] if item != soonestDepartureTimeUnix)
minutes = int((soonestDepartureTimeUnix2 - (time.time()))/60)
然而这只是再次返回 0。
在生成器中,忽略当前时间之前或等于当前时间的任何时间。
minAllowedDepartureTimeUnix = time.time() + 60
soonestDepartureTimeUnix = min(item["departure_time"]
for item in tsl105513Route2["itineraries"][0]["schedule_items"]
if item["departure_time"] >= minAllowedDepartureTimeUnix)