0

在我目前正在解决的问题中,涉及公共汽车,因此有望清除代码中提到的停靠点和路线。

所以本质上我想用这个功能实现的是让下一站停下来。我已经解决了这个问题的大约 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。

然后,我尝试遍历matchedRoute 以查找该路线中的停靠点,并且我需要基于此检索下一个停靠点。

4

1 回答 1

1

你可以这样做:

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")
于 2019-10-18T05:33:04.667 回答