[英]IndexError: list index out of range Python 2.7.x
I am going through chapter 8 of Python for Informatics and have been asked for an exercise to rewrite the following function: 我正在阅读Python for Informatics的第8章,并被要求做一个练习来重写以下函数:
fhand = open('mbox-short.txt')
count = 0
for line in fhand:
words = line.split()
#print 'Debug:', words
if len(words) == 0:
continue
if words[0] != 'From':
continue
print words[2]
I was asked to rewrite it using a single compound if
statement, so I wrote the following: 我被要求使用单个复合if
语句重写它,所以我写了以下内容:
fhand = open('mbox-short.txt')
#count = 0 <-- not even sure why this is in the orginal
for line in fhand:
words = line.split()
print 'Debug:', words
if len(words) == 0 and words[0] != 'From':
continue
print words[2]
The first function works just fine, but the second gives me the following error: 第一个函数工作正常,但是第二个函数却给我以下错误:
Traceback (most recent call last):
File "ch8.py", line 258, in <module>
print words[2]
IndexError: list index out of range
I do not understand why what I wrote is returning the error, as far as I can tell I am doing the same exact thing, but apparently I am wrong, I just don't understand why. 据我所知,我不知道为什么我写的东西会返回错误,但我显然是错的,我只是不明白为什么。 Maybe there is a subtle issue that I am just not picking up on. 也许有一个微妙的问题,我只是不了解。
Thank you, 谢谢,
UPDATE 更新
Instructions 'use a compound logical expression using the and
logical operator with a single if
statement. 指令'通过一个单独的if
语句使用and
逻辑运算符使用复合逻辑表达式。
In the original code 在原始代码中
if len(words) == 0:
continue
if words[0] != 'From':
continue
You reach continue
in either case. 无论哪种情况,您都可以continue
。 Therefore the single line version should be 因此,单行版本应为
if len(words) == 0 or words[0] != 'From':
# ^ or, not and
continue
If you need to use and
, more refactoring is needed, switching the print
and (now-implicit) continue
and reversing the tests: 如果需要使用and
,则需要更多的重构,请切换print
并continue
(现在是隐式的)并反转测试:
if len(words) > 0 and words[0] == 'From':
print words[2]
fhand = open('mbox-short.txt')
for line in fhand:
words = line.split()
print 'Debug:', words
if len(words) == 0 or words[0] != 'From':
continue
print words[2]
Change and
to or
. 更改为and
or
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.