对不起,如果这个问题已经被问过了,但我找不到任何解决我问题的答案。 我正在Mac上使用Python3.8和PyCharm(如果这些信息有帮助的话)。 我刚开始学习python,有扎实的C和MatLab背景。 我的目标是从以下格式的文件中读取有关火车站的一些信息 然后向用户询问一个车站,并给出通过火车连接的车站的名称。这是我的密码:
fin = open('trains', 'r')
string = fin.read()
lines = string.split('\n')
print(lines)
station = input("Insert station name\n")
from_station = [] #stations from which trains arrive at the user's station
to_station = [] #stations to which trains arrive from user's station
for i in range(0,len(lines)):
words = lines[i].split()
for i in range(0,4):
print(words[i]) #put to check if the words list actually stores the different words
if words[0] == station:
to_station.append(words[2])
if words[2] == station:
from_station.append(words[0])
print("Trains arriving from stations: ")
print(from_station)
print("Trains going to stations: ")
print(to_station)
fin.close()
即使我的编译器(或解释器)能够毫无问题地打印出正确的信息,我仍然会在第17行中获取print(words[i])
的索引越界错误。
在for结束后,我无法编译代码
提前感谢您的帮助
编辑:即使我做了你建议的更正——我没有注意到内部循环中的那个错误——我仍然不断地得到那个错误。即使我完全删除了那个内部循环,我也会得到那个错误
问题来自您的内部循环以及列表单词上的迭代器。您可能有一个包含两个单词的列表,然后可能会出现索引越界错误
在内部循环中使用除“i”之外的其他变量
问题就在这一行
每次都需要检查
len(words)
,并且需要确认len(words)
在索引范围内 准确查看数据可以解决此问题相关问题 更多 >
编程相关推荐