为什么我在代码中收到"列表索引超出范围"?

And*_*car 2 python indexing error-handling list range

我收到"列表索引超出范围".我想我正在错误地命名其中一个变量.如果我在其中添加其余内容可能会更有意义.

我试图打印出列表中坐标的差异.我确定它搞砸了str(distance_list[i]).

相关代码:

# Get the maximum distance from the user
maxDistance = float(raw_input("What is the maximum distance from the base?"))

# Set the base N,E values
#baseEasting = float(raw_input("What is the easting of the base?"))
#baseNorthing = float(raw_input("What is the northing of the base?"))
baseEasting = "346607"
baseNorthing="6274191"

#TODO: Place the values for meterological stations into the lists
stationCoords = [ [476050, 7709929],[473971,7707713],[465676,7691097] ,[515612,7702192] ,[516655,7704405],[519788,7713255],[538466,7683341] ]
numCoords = len(stationCoords)

distance_list = []
for i in range (0, numCoords):
    stationNorthing=stationCoords[i][0]
    stationEasting=stationCoords[i][1]
    distance = calculateDistance(stationNorthing, stationEasting, EASTING_BASE, NORTHING_BASE)
    if distance <= maxDistance:
# Calculate output string
        strTextOut = "Co-ordinates: " + str(distance_list[i])
        + ", at: " + str(round(distance, 0)) + " m"
        # Output the string
        print(strTextOut)
Run Code Online (Sandbox Code Playgroud)

希望这一切都是相关的.但是车站的Coords已经有了价值.

int*_*jay 5

distance_list是一个空列表(因为该行distance_list = []),并且您正在尝试从中读取值distance_list[i].这保证会失败,因为列表为空,因此没有索引有效.

也许你想打字stationCoords[i]呢?这更有意义,因为您试图在那里打印坐标.