【发布时间】:2014-01-16 04:39:48
【问题描述】:
我正在阅读 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
我不明白为什么我写的东西会返回错误,据我所知我正在做同样的事情,但显然我错了,我只是不明白为什么。也许有一个我没有注意到的微妙问题。
谢谢,
更新
指令'使用复合逻辑表达式,使用 and 逻辑运算符和单个 if 语句。
【问题讨论】:
标签: python list python-2.7 indexing