Python作业:实现根据地铁站代码返回元组内索引的函数并排查报错
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

