为什么这个指数超出范围?

时间:2013-08-06 10:18:18

标签: python

所以我基本上我希望它循环三次,你可以看到我在范围3中有选择= 0,1,2和m所以这应该循环三次,首先选择0然后选择1然后选择二。那为什么这个超出范围?

Pythons确切的错误返回:

choices[r]=p.nextInt()
IndexError: list assignment index out of range

请忽略p.next因为我们必须在uni处写它,因为我们有自己的模块。

这是我的代码

cities=["Coventry", "Birmingham", "Wolverhampton", "Leicester"]
distances=[
    [0,25,33,24],
    [25,0,17,42],
    [33,17,0,54],
    [24,42,54,0]]

def distancesthree():
    choices=[0,1,2] 
    for m in range(3): #This will loop three times!
        for r in range(len(cities)):
            p.write ("%d : %s\n" %(r, cities[r]))
        p.write("\nEnter city number %d: \n"%(m+1))
        choices[r]=p.nextInt()

3 个答案:

答案 0 :(得分:2)

您是否可能使用了错误的变量 - 可能您想写m而不是r

choices[m]=p.nextInt()

答案 1 :(得分:1)

当您在整个地方使用单字母名称时会发生这种情况...
最后一行中的r应替换为m

但我编辑了你的代码,告诉你它应该如何编写。

cities = ("Coventry", "Birmingham", "Wolverhampton", "Leicester")
distances = [
    [0, 25, 33, 24],
    [25, 0, 17, 42],
    [33, 17, 0, 54],
    [24, 42, 54, 0],
]

def chooseDistances():
    choices = [0, 1, 2] 
    for choiceIndex in range(3):
        for cityIndex, cityName in enumerate(cities):
            p.write("%d : %s\n"%(cityIndex, cityName))
        p.write("\nEnter city number %d: \n"%(step+1))
        choices[choiceIndex] = p.nextInt()

然后你永远不会使用cityIndex作为选择,或者使用choiceIndex作为城市......

答案 2 :(得分:0)

for r in range(len(cities)):之后,r将为3,因为这是range(len(cities))列表中的最后一项。

因此,当您执行choices[r]时,您尝试执行choices[3],但列表只会达到索引2.

也许你的意思是choices[r-1]?或者甚至说for r in range(len(cities) - 1):?甚至是choices[m]

相关问题