【问题标题】:IndexError: list index out of range when using tuplesIndexError:使用元组时列表索引超出范围
【发布时间】:2020-08-07 18:06:55
【问题描述】:

我很困惑。我在第 43 行收到一条错误消息,指出列表索引超出范围。任何帮助表示赞赏。

def tokenize(lines):
words = []
for line in lines:
    start = 0
    end = start + 1
    while start < len(line):
        character = line[start]
        if character.isspace():
            end += 1
        elif character.isalpha():
            end = start + 1
            while end < len(line) and line[end].isalpha():
                end += 1
            words.append(line[start:end].lower())
        elif character.isdigit():
            end = start + 1
            while end < len(line) and line[end].isdigit():
                end += 1
            words.append(line[start:end])
        else:
            end += 1
            words.append(line[start:end])
        start = end
return words


def countWords(words, stopWords):
    wordDict = {}
    for word in words:
        if word in stopWords:
            continue
        elif not word in wordDict:
            wordDict[word] = 1
        else:
            frequency = wordDict.get(word)
            wordDict[word] = frequency + 1
    return wordDict


def printTopMost(frequencies, n):
    listOfTuples = sorted(frequencies.items(), key=lambda x:x[1], reverse=True)
    for x in range(n):
        pair = listOfTuples[x]
        word = pair[0]
        frequency = str(pair[1])
        print(word.ljust(20), frequency.rjust(5))

pair = listOfTuples[x] 给我一个错误。请帮助我,为什么我必须添加这么多文字,它说的主要是代码。

这就是函数的调用方式:(test.py)还有我创建的其他函数的说明,比如 tokenize 和 countWords,但我得到的错误不是我的一部分,这就是我的原因我已经把它们排除在外了。

def printTopMost(freq,n):
    saved = sys.stdout
    sys.stdout = io.StringIO()
    wordfreq.printTopMost(freq,n)
    out = sys.stdout.getvalue()
    sys.stdout = saved
    return out


    test(printTopMost,({"horror": 5, "happiness": 15},0),"")
    test(printTopMost,({"C": 3, "python": 5, "haskell": 2, "java": 
    1},3),"python                  5\nC                       3\nhaskell                 
    2\n")

完整的错误信息

Traceback (most recent call last):
  File "C:/Users/Daniel/Documents/Scripts/Chalmers/lab1/test.py", line 81, in <module>
    run()
  File "C:/Users/Daniel/Documents/Scripts/Chalmers/lab1/test.py", line 70, in run
    test(printTopMost,({},10),"")
  File "C:/Users/Daniel/Documents/Scripts/Chalmers/lab1/test.py", line 8, in test
    z = fun(*x)
  File "C:/Users/Daniel/Documents/Scripts/Chalmers/lab1/test.py", line 41, in printTopMost
    wordfreq.printTopMost(freq,n)
  File "C:\Users\Daniel\Documents\Scripts\Chalmers\lab1\wordfreq.py", line 4, in printTopMost
    pair = listOfTuples[x]
IndexError: list index out of range
Condition failed:
   printTopMost({'horror': 5, 'happiness': 15}, 0) == ''
printTopMost returned/printed:
happiness               15
horror                   5

Condition failed:
   printTopMost({'C': 3, 'python': 5, 'haskell': 2, 'java': 1}, 3) == 'python                  5\nC                       3\nhaskell                 2\n'
printTopMost returned/printed:
python                   5
C                        3
haskell                  2
java                     1

https://i.imgur.com/9SciXtx.png

【问题讨论】:

  • 请发布完整的错误信息。还有你是怎么调用这些函数的?
  • assert len(listOfTuples) == n, "length isn't what you are expecting"
  • 文件“C:\Users\Documents\Scripts\Chalmers\lab1\wordfreq.py”,第 43 行,在 printTopMost 对 = listOfTuples[x] IndexError: list index out of range I'm call函数在一个单独的文件中。
  • @Grevus 您需要在问题本身中包含minimal reproducible example。顺便说一句,欢迎来到 SO!如果您需要建议,请查看 tourHow to Ask
  • 请将代码发布在何处以及如何调用该函数。您似乎传递了错误/不正确的参数

标签: python indexing tuples range


【解决方案1】:
def printTopMost(frequencies, n):
    listOfTuples = sorted(frequencies.items(), key=lambda x:x[1], reverse=True)
    n=min(n,len(listOfTuples))
    for x in range(n):
        pair = listOfTuples[x]
        word = pair[0]
        frequency = str(pair[1])
        print(word.ljust(20), frequency.rjust(5))

简单的破解

【讨论】:

  • 这修复了错误消息,但也不能正确打印所有内容。条件失败:printTopMost({'horror': 5, 'happiness': 15}, 0) == '' printTopMost 返回/打印:幸福 15 恐怖 5 条件失败:printTopMost({'C': 3, 'python': 5, 'haskell': 2, 'java': 1}, 3) == 'python 5\nC 3\nhaskell 2\n' printTopMost 返回/打印:python 5 C 3 haskell 2 java 1
  • 我将在原帖底部添加输出。
  • @Grevus 请试试这个
  • 删除了一个错误,条件失败:printTopMost({'C': 3, 'python': 5, 'haskell': 2, 'java': 1}, 3) == 'python 5\nC 3\nhaskell 2\n' printTopMost 返回/打印:python 5 C 3 haskell 2 仍然存在
  • 打印如愿以偿,那条件是怎么失败的呢?另外,请将此图片添加到问题中,以便其他人也可以看到
猜你喜欢
  • 2013-07-28
  • 2018-11-16
  • 2017-07-12
  • 2017-05-25
  • 1970-01-01
  • 2011-10-31
  • 2015-06-26
相关资源
最近更新 更多