我正在阅读 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]
我被要求使用单个复合 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]
第一个函数工作正常,但第二个函数出现以下错误:
Traceback (most recent call last):
File "ch8.py", line 258, in <module>
print words[2]
IndexError: list index out of range
我不明白为什么我写的东西会返回错误,据我所知我正在做同样的事情,但显然我错了,我只是不明白为什么。也许有一个微妙的问题我没有注意到。
谢谢,
更新
Instructions '使用复合逻辑表达式,使用 and 逻辑运算符和单个 if 语句。
请您参考如下方法:
在原始代码中
if len(words) == 0:
continue
if words[0] != 'From':
continue
在任一情况下,您都到达了continue。因此单行版本应该是
if len(words) == 0 or words[0] != 'From':
# ^ or, not and
continue
如果您需要使用and,则需要进行更多重构,切换print 和(现在隐含的)continue 并反转测试:
if len(words) > 0 and words[0] == 'From':
print words[2]
