在我目前正在解决的问题中,涉及公共汽车,因此有望清除代码中提到的站点和路线。
所以本质上我试图用这个功能实现的是让下一站停下来。我已经解决了这个问题的大约 80%,但仍然坚持到下一站
def nextstop(stops,routes,stopX,routeX):
matchedRoute = []
matchedstop = []
for i in routes:
if routeX in i:
matchedRoute = i
for i in matchedRoute[1]:
if i == stopX[0]:
matchedstop = next(iter(matchedRoute))
print(matchedstop)
因此,假设我正在对这个元组进行操作:
('Route 5', [1118, 1114, 1115, 533, 1370, 1091, 2363, 1296, 1298, 763, 852, 851, 995, 815, 814, 848, 846, 845, 842, 841, 838, 822, 819, 818, 997, 996, 767, 622, 621, 620, 1082])
我所拥有的是我想要匹配的止损,例如 [1115[. 我需要以某种方式返回下一站 [533]。
但我的代码返回元组“Route 5”的开头
这就是我遇到麻烦的地方,我将如何反对获取序列中的下一个元素?
编辑:按要求澄清
在 Ipython 中,我会这样解析函数 python nextstop(stops,routes,stops[533],'Route 5')
第一个循环采用我在 csv 文件中拥有的大量元组列表,并遍历它们与路由名称的模式匹配。当它匹配时,它将该元组存储为matchedRoute。
然后我试图遍历匹配的路线以找到该路线中的停靠点,我需要基于此检索下一停靠点。
你可以这样做:
def nextstop(stops,routes,stopX,routeX):
matchedRoute = []
matchedstop = []
for i in routes:
if routeX in i:
matchedRoute = i
if stopX[0] in matchedRoute[1]:
if matchedRoute[1].index(stopX[0]) == len(matchedRoute[1]):
matchedstop = "This is the last stop"
else:
matchedstop = matchedRoute[1][matchedRoute[1].index(stopX[0])+1]
else:
matchedstop = "Stop not found in route"
print(matchedstop)
我无法测试这个确切的代码,因为我不知道输入,但我可以给你一个例子,它是如何工作的:
tup1 = ('Route 5', [1118, 1114, 1115, 533, 1370, 1091, 2363, 1296, 1298, 763, 852, 851, 995, 815, 814, 848, 846, 845, 842, 841, 838, 822, 819, 818, 997, 996, 767, 622, 621, 620, 1082])
route = 'Route 5'
stop = 1115
r_x, s_x = tup1
if r_x == route:
if stop in s_x:
print(s_x[s_x.index(stop)+1])
输出:
533
list.index(elem)
方法返回元素在列表中第一次出现的索引。因此,如果您访问下一个索引,即通过向其添加一个,您可以获得下一个索引。这样你就不需要在停靠点上循环。
编辑:
#Example:
>>> routes = [('Route 5', [1118, 1114, 1115, 533, 1370, 1091, 2363, 1296, 1298, 763, 852, 851, 995, 815, 814, 848, 846, 845, 842, 841, 838, 822, 819, 818, 997, 996, 767, 622, 621, 620, 1082]),('Route 4', [1118, 1114, 1115, 533, 1370, 1091, 2363, 1296, 1298, 763, 852, 851, 995, 815, 814, 848, 846, 845, 842, 841, 838, 822, 819, 818, 997, 996, 767, 622, 621, 620, 1082])]
>>> nextstop(1,routes,[1115],'Route 5')
533
编辑 2:更简短的答案是:
def nextstop(stops,routes,stopX,routeX):
for route, stop in routes:
if route == routeX:
if stopX[0] in stop:
try:
print(stop[stop.index(stopX[0])+1])
Except IndexError:
print("This is the last stop")
else:
print("Stop not found")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句