【发布时间】:2017-06-22 15:25:16
【问题描述】:
我是 python 新手,使用 Jupityr 笔记本在 edx 上做一些基本的编码作业。我在一项我无法弄清楚的作业中遇到了索引错误。作业让我在 while 循环中一次读取一行文本文件,并以特定格式打印输出。我的代码如下
city_temp = mean_temp.readline().strip().split(',')
while city_temp:
print (headings[0].title(), "of", city_temp[0], headings[2], "is", city_temp[2], "Celsius")
city_temp = mean_temp.readline().strip().split(',')
代码运行整个文件,但不是在空行结束“while”循环,而是继续运行并创建一个空列表。我不确定为什么会发生这种情况,也无法自己解决。我尝试为空字符串添加“if”测试并中断,并且还编写了额外的空文本行,但没有一个选项导致任何成功。如果有人有想法,我将不胜感激!
我也有一个 txt 文件包含的内容的摘录粘贴在下面。还有其他城市,但我认为没有必要将每个城市都包括在内:
city,country,month ave: highest high,month ave: lowest low
Beijing,China,30.9,-8.4
这是我得到的索引错误:(抱歉格式不好,仍在学习
IndexError Traceback (most recent call last)
<ipython-input-18-6ea7e8e263b5> in <module>()
5 while city_temp:
6
----> 7 print (headings[0].title(), "of", city_temp[0], headings[2], "is", city_temp[2], "Celsius")
8 city_temp = mean_temp.readline().strip().split(',')
9
IndexError: list index out of range
【问题讨论】:
-
要真正解决您的 IndexError,请将您的整个错误消息(包括回溯)编辑到您的问题中。如果 city_temp 正在读取一个空行,它应该是一个空列表(strip() 会在拆分发生之前删除任何空白字符),所以这里还有其他事情发生。
-
@AlanLeuthard 我已经附上了我之前遇到的整个错误,我很好奇为什么会发生这个错误
-
啊啊啊……刚刚测试过了。 'empty_string.split()' 返回一个空列表。 'empty_string.split(',')' 返回一个包含空字符串的列表。该列表不为空,因此 city_temp 为 True。将 'while city_temp' 更改为 'while city_temp[0]' 以检查列表中的内容是否为空。或者使用 try 块。
-
做到了!如果没有你的帮助,我永远不会意识到这一点。再次感谢!
-
我添加到答案顺便说一句,为了后代。
标签: python indexoutofboundsexception readline