【问题标题】:IndexError: list index out of range Python 2.7.xIndexError:列表索引超出范围 Python 2.7.x
【发布时间】: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


    【解决方案1】:
    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]
    

    and 更改为or

    【讨论】:

    • 效果很好,但我被指示使用 and 运算符,除非它是书中的错字
    【解决方案2】:

    在原代码中

        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]
    

    【讨论】:

    • 效果很好,但我被指示使用and 运算符,除非它是书籍拼写错误
    猜你喜欢
    • 2019-05-18
    • 1970-01-01
    • 2020-03-16
    • 2016-08-25
    • 2017-04-05
    • 2012-07-15
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多