Python:列出索引超出范围,即使我正在查看索引为0的元素

Python:列出索引超出范围,即使我正在查看索引为0的元素,python,Python,对不起,如果这个问题已经被问过了,但我找不到任何解决我问题的答案。 我正在Mac上使用Python3.8和PyCharm(如果这些信息有帮助的话)。 我刚开始学习python,有扎实的C和MatLab背景。 我的目标是从以下格式的文件中读取有关火车站的一些信息 然后向用户询问一个车站,并给出通过火车连接的车站的名称。这是我的密码: fin = open('trains', 'r') string = fin.read() lines = string.split('\n') print(line

对不起,如果这个问题已经被问过了,但我找不到任何解决我问题的答案。 我正在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”之外的另一个变量。

问题来自内部循环以及列表单词上的迭代器。您可能有一个包含两个单词的列表,然后可能会出现索引越界错误

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 j in range(0,len(words)):
        print(words[j]) #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()
问题就在这一行

words = lines[i].split()
您需要每次检查
len(words)
,并需要确认
len(words)
在您的索引范围内
准确查看您的数据可以解决问题

您确定
单词
是一个数组吗?
对于范围(0,4)中的i:print(words[i])
嗯,刚开始,您如何知道单词的长度?如果长度是2…那么你现在得到了你现在得到的你的第二个循环使用的是相同的interator
i
请显示错误内部
i
不是问题。
range
函数将返回正确的值,即使在循环内部修改了
i
。示例:我知道有四个元素,因为我知道输入的格式。我设法打印单词的内容,一旦我离开外部循环,我就会得到那个错误。