查找lis中的下一个元素

2024-05-23 19:41:47 发布

您现在位置:Python中文网/ 问答频道 /正文

在这个问题上,我目前正在解决涉及巴士,以便有希望清除提到的车站和路线的代码。你知道吗

所以本质上,我想用这个函数来实现的是,让下一站停下来。我已经通过了大约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]。我需要的是返回下一站。你知道吗

但是我的代码返回元组'Route 5'的开头

这就是我遇到麻烦的地方,我怎么能反对得到序列中的下一个元素呢?你知道吗

编辑:按要求澄清

在Ipython中,我会这样解析函数 python nextstop(stops,routes,stops[533],'Route 5')

第一个循环获取csv文件中的大量元组列表,并根据路由的名称对它们进行模式匹配。当它匹配时,它将该元组存储为matchedRoute。你知道吗

然后,我尝试遍历matchedRoute以找到该路径中的站点,并需要根据该路径检索下一个站点。你知道吗


Tags: 函数代码in路径forifroute元组
1条回答
网友
1楼 · 发布于 2024-05-23 19:41:47

您可以这样做:

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")

相关问题 更多 >