Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么该指数超出范围?_Python - Fatal编程技术网

Python 为什么该指数超出范围?

Python 为什么该指数超出范围?,python,Python,所以我基本上希望它循环三次,正如你所看到的,我有选项=0,1,2,对于m,在范围3内,所以这应该循环三次,首先是选项0,然后是选项1,然后是选项2。那么为什么这超出了范围呢 Pythons精确错误返回: choices[r]=p.nextInt() IndexError: list assignment index out of range 请忽略p.next,因为这是我们必须在uni编写它的方式,因为我们有自己的模块 这是我的密码 cities=["Coventry", "Birmingha

所以我基本上希望它循环三次,正如你所看到的,我有选项=0,1,2,对于
m
,在范围3内,所以这应该循环三次,首先是选项0,然后是选项1,然后是选项2。那么为什么这超出了范围呢

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()

在范围(len(cities))中r的
之后:
r
将是
3
,因为这是范围(len(cities))列表中的最后一项

因此,当您执行
选择[r]
时,您正试图执行
选择[3]
,但列表仅上升到索引2


也许你的意思是选择[r-1]?或者甚至对范围内的r(len(cities)-1)说
?或者甚至是
choices[m]

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

choices[m]=p.nextInt()

这就是当你到处使用单字母名称时会发生的情况…
最后一行中的
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进行城市…

按索引迭代是灾难的一个秘诀-Python是为按值迭代而设计的。它更快、更灵活、更容易阅读,而且你永远不会出现索引错误?它有一个
nextInt
方法。。。?它是
java.util.Scanner
的某种Python实现吗?(它不可能完全是
Scanner
,因为它有
write
。不过,我很好奇,这是否是要求您使用的某个交互帮助程序库。它看起来可能比
raw\u input
更好,尽管不像Pythonic)这就是当你在所有地方都使用单字母名称时会发生的情况……谢谢你,海德罗,你说得对@ilius同意,变量名应该是有意义的。这就是避免创建冗余变量的方法-您只需首先考虑名称:)