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

2024-05-14 14:25:38 发布

您现在位置:Python中文网/ 问答频道 /正文

对不起,如果这个问题已经被问过了,但我找不到任何解决我问题的答案。 我正在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结束后,我无法编译代码

提前感谢您的帮助

编辑:即使我做了你建议的更正——我没有注意到内部循环中的那个错误——我仍然不断地得到那个错误。即使我完全删除了那个内部循环,我也会得到那个错误

This is the image of the code that I run, which is the one above after making the correction suggested in the first answers/comments


Tags: thetofrom信息forif错误words
3条回答

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

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

在内部循环中使用除“i”之外的其他变量

问题就在这一行

words = lines[i].split()

每次都需要检查len(words),并且需要确认len(words)在索引范围内 准确查看数据可以解决此问题

相关问题 更多 >

    热门问题