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

时间:2013-05-23 14:24:15

标签: python list error-handling indexing 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)

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

2 个答案:

答案 0 :(得分:5)

distance_list是一个空列表(由于行distance_list = []),您尝试使用distance_list[i]从中读取值。这保证会失败,因为列表为空,因此没有索引有效。

也许你打算改为输入stationCoords[i]?这更有意义,因为你试图在那里打印坐标。

答案 1 :(得分:2)

您可能想要添加:

distance_list.append(distance)

在你的if陈述之前,或类似的,或者只是替换:

str(distance_list[i])

str(distance)

并完全摆脱distance_list,如果您以后不需要访问距离。

相关问题