You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python作业:实现根据地铁站代码返回元组内索引的函数并排查报错

Fixing the ValueError in get_station_position

Hey there! Let's break down why your code is throwing that ValueError and fix it properly.

The Root Cause

The error comes directly from this line:

index = line.index(i)

Remember how your line tuple is structured:

  • line[0]: The string name of the line ("S Line")
  • line[1]: The nested tuple holding all station tuples

When you loop through line[1], each i is a station tuple like ('S3', 'National Theatre'). This i only lives inside line[1], not in the top-level line tuple. So trying to call line.index(i) will never find the element, hence the "tuple.index(x): x not in tuple" error.

Solution 1: Quick Fix for the Index Lookup

The simplest fix is to target the station list (line[1]) instead of the entire line tuple when looking up the index:

def get_station_position(line, station_code):
    for i in line[1]:
        if i[0] == station_code:
            index = line[1].index(i)  # Changed line.index(i) to line[1].index(i)
            return index
    return -1  # No need for int(-1) — -1 is already an integer

Solution 2: Cleaner & More Efficient with enumerate

While the first fix works, using enumerate is a better approach. It lets you grab both the index and station tuple in one loop, so you don’t need to run an extra .index() search:

def get_station_position(line, station_code):
    for idx, station in enumerate(line[1]):
        if station[0] == station_code:
            return idx
    return -1

Testing the Fix

Let’s verify with your sample data:

line = ('S Line', (('S2', 'Dairy Park'), ('S3', 'National Theatre'), ('S4', 'Commerce')))

print(get_station_position(line, 'S3'))  # Returns 1 (correct!)
print(get_station_position(line, 'S5'))  # Returns -1 (correct!)

Both solutions will resolve the ValueError and behave exactly as you need. The enumerate version is more readable and efficient, which is always a plus in Python!

内容的提问来源于stack exchange,提问作者a9302c

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 10:58:11