Python 列表索引超出范围(使用while循环)

Python 列表索引超出范围(使用while循环),python,list,indexing,Python,List,Indexing,我正在为edx课程做a作业,当代码运行while循环时,我的代码中出现了“索引超出范围”错误,尽管它最终给出了正确的输出 这是我的代码: # [] create The Weather # [] copy and paste in edX assignment page !curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/world_temp_mean.csv -o mean_temp.txt

我正在为edx课程做a作业,当代码运行while循环时,我的代码中出现了“索引超出范围”错误,尽管它最终给出了正确的输出

这是我的代码:

# [] create The Weather
# [] copy and paste in edX assignment page
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/world_temp_mean.csv -o mean_temp.txt

mean_temp = open('mean_temp.txt', 'a+')
mean_temp.write("Rio de Janeiro,Brazil,30.0,18.0\n")

mean_temp.seek(0)

headings = mean_temp.readline().split(',')

city_temp = mean_temp.readline().split(',')
while city_temp:
    print(headings[0].capitalize(), "of", city_temp[0], headings[2], "is", city_temp[2], "Celsius")
    city_temp = mean_temp.readline().split(',')

mean_temp.close()

我已经测试过了,应该可以用了。我认为您的while子句没有正确地找到文件的结尾-for循环可以工作并且更干净

以“平均温度”作为f:
f、 写(“\nRio de Janeiro,巴西,30.0,18.0”)
打开(“平均温度txt”、“r”)作为f:
headers=f.readline().split(','))
对于f中的下一行:
下一行=下一行。拆分(',')
打印(标题[0]。大写(),“of”,下一行[0],标题[2],“is”,下一行[2],“Celsius”)

当您点击最后一行空行,即
'
,mean_temp.readline().split(',')的结果是
[']
,而不是
[]
,因此您的循环将继续,并且您将得到索引错误。您可以改为检查
len

while len(city_temp) == 4:
    print(headings[0].capitalize(), "of", city_temp[0], headings[2], "is", city_temp[2], "Celsius")
    city_temp = mean_temp.readline().split(',')
但是,更好的处理方法是使用适当的
for
循环和
csv
读取器:

import csv
with open('mean_temp.txt') as f:
    reader = csv.reader(f)
    header = next(reader)
    for city in reader:
        print(header[0].capitalize(), "of", city[0], header[2], "is", city[2], "Celsius")

(如果使用
读写器,文件格式会更好,但打印那一行的方式不行。)

你能澄清一下吗?仅仅说“它有一个xxx错误”并不是一个明确的问题陈述。请演示一个。不是特定问题的解决方案,但您可以通过将while循环和readline替换为
for line in mean\u temp:
来简化代码,并使问题更容易诊断。提示:只要插入
print(city\u temp),您就可以立即知道问题出在哪里
就在现有打印语句之前。这不需要几秒钟。在while循环中打印语句之前,如果len(headings)>0,请使用
,这样您应该很好。这不起作用,可能是因为文件末尾有一个额外的行或其他东西。当文件末尾没有空行时,同样的问题似乎也会发生。@tobias_k我已经编辑了答案,现在应该可以了。请告诉我,谢谢!我只是不明白最后一行中的['''是从哪里来的。@Renves好吧,你的文件中的最后一行是空行,即
'
,如果你用
'分割它,'
(或其他任何东西),你会得到
[']
,也就是说,一段就是整行。