我已经看过在网站上发布的其他问题有关索引错误,但我仍然不知道如何解决我自己的代码。当谈到Python时,我是一名初学者。根据用户的输入,我想检查输入是否位于列表中每行的第四个位置。IndexError:列表索引超出范围列表中的for循环
下面的代码:
#create a list of lists from the missionPlan.txt
from __future__ import with_statement
listoflists = []
with open("missionPlan.txt", "r") as f:
results = [elem for elem in f.read().split('\n') if elem]
for result in results:
listoflists.append(result.split())
#print(listoflists)
#print(listoflists[2][3])
choice = int(input('Which command would you like to alter: '))
i = 0
for rows in listoflists:
while i < len(listoflists):
if listoflists[i][3]==choice:
print (listoflists[i][0])
i += 1
这是我不断收到错误:
not getting inside the if statement
首先,'choice'已经是一个整数,所以你不需要'int再次选择)。此外,你的for循环是错误的。你在每次添加一个之后就设置'i = 0',所以它总是为零。修正你的缩进也许? – mbomb007
我已经提出了建议的更改,它仍然给我同样的错误@ mbomb007 – Allie
你不需要stackoverflow;你可以自己解决这个问题。 “i”太大,或者“3”太大。输入一些打印语句来查看数据是什么,然后找出哪个数字太大。不要忘记:计数从零开始,所以如果列表中有三项,则可以使用的最大索引是2. –