<p>对不起,如果这个问题已经被问过了,但我找不到任何解决我问题的答案。
我正在Mac上使用Python3.8和PyCharm(如果这些信息有帮助的话)。
我刚开始学习python,有扎实的C和MatLab背景。
我的目标是从以下格式的文件中读取有关火车站的一些信息
<em></em>
然后向用户询问一个车站,并给出通过火车连接的车站的名称。这是我的密码:</p>
<pre><code>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()
</code></pre>
<p>即使我的编译器(或解释器)能够毫无问题地打印出正确的信息,我仍然会在第17行中获取<code>print(words[i])</code>的索引越界错误。
在for结束后,我无法编译代码</p>
<p>提前感谢您的帮助</p>
<p>编辑:即使我做了你建议的更正——我没有注意到内部循环中的那个错误——我仍然不断地得到那个错误。即使我完全删除了那个内部循环,我也会得到那个错误</p>
<p><a href="https://i.stack.imgur.com/uoj0U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uoj0U.png" alt="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"/></a></p>