【问题标题】:Python: IndexError: list index out of range ErrorPython:IndexError:列表索引超出范围错误
【发布时间】:2013-07-05 00:08:32
【问题描述】:

更新了,往下看!

我被困住了!我得到一个 IndexError: list index out of range 错误。

def makeInverseIndex(strlist):
    numStrList = list(enumerate(strlist))
    n = 0 
    m = 0 
    dictionary = {}
    while (n < len(strList)-1):
        while (m < len(strlist)-1):
            if numStrList[n][1].split()[m] not in dictionary:
                dictionary[numStrList[n][1].split()[m]] = {numStrList[n][0]}
                m = m+1
            elif {numStrList[n][0]} not in dictionary[numStrList[n][1].split()[m]]:
                dictionary[numStrList[n][1].split()[m]]|{numStrList[n][0]} 
                m = m+1
        n = n+1                
return dictionary

它给了我这个错误

>>> makeInverseIndex(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "./inverse_index_lab.py", line 23, in makeInverseIndex
    if numStrList[n][1].split()[m] not in dictionary: 
IndexError: list index out of range

我不明白...是什么原因造成的?即使我更改了 while 循环的条件,它也会发生。我不明白有什么问题。我对此很陌生,所以请像一块西兰花问你这个问题一样解释它。

编辑:

谢谢大家,我忘了说输入的例子,我想输入这样的东西:

 L=['A B C', 'B C E', 'A E', 'C D A']

并将其作为输出:

D={'A':{0,2,3}, 'B':{0,1}, 'C':{0,3}, 'D':{3}, 'E':{1,2}}

例如,创建一个字典,显示在列表中您可能会找到“A”的位置。它应该与一个巨大的列表一起工作。有没有人有任何提示?我希望它迭代并挑选出每个字母,然后为它们分配一个字典值。

编辑二:

感谢你们的大力帮助,我的代码看起来很漂亮:

def makeInverseIndex(strList):
numStrList = list(enumerate(strList))
n = 0
dictionary = {}
while (n < len(strList)):
    for word in numStrList[n][1].split():
        if word not in dictionary:
            dictionary[word] = {numStrList[n][0]}
        elif {numStrList[n][0]} not in dictionary[word]:
            dictionary[word]|={numStrList[n][0]} 
    n = n+1                     

return dictionary

但是当我尝试运行该模块时,我仍然设法得到这个错误:

   >>> makeInverseIndex(L)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "./inverse_index_lab.py", line 21, in makeInverseIndex
    for word in numStrList[n][1].split():
NameError: global name 'StrList' is not defined

我看不出错误来自哪里。

【问题讨论】:

  • numStrList[n][1].split()[m] - 你在这里有三个索引:n、1、m - 它们中的每一个都可能导致这个错误 - 这种行为完全取决于输入数据 - 检查你 numStrList 包含的内容print numStrList .
  • 不相关但可以将while (n &lt; len(StrList)-1):中的StrList修改为strlist
  • 谢谢@misguided 我没看到那个

标签: python list python-3.x


【解决方案1】:

很高兴看到一些聪明的蔬菜编程。

首先,你的问题。就像@Vasiliy 所说,你有 3 个索引。 n 没问题,因为您使用 while 条件保护它。 1 很好,因为 enumerate 总是生成两件事。那只剩下m。这是你的问题。

假设您在strlist 中有N 元素。对于strlist 中的每个元素e,您将split() 应用于它。 e.split() 中的元素数并不总是等于Nm 的 while 条件防范 N,而不是 len(e.split()),因此索引超出范围。

要解决这个问题,首先拆分字符串,然后循环遍历它。当您使用它时,不妨完全摆脱m,只将字符串拆分一次,并获得一些性能。另外,您永远不会重置您的m,它只会不断增长。

while (n < len(strList)):
    for word in numStrList[n][1].split():
        if word not in dictionary:
            dictionary[word] = {numStrList[n][0]}
        elif {numStrList[n][0]} not in dictionary[word]:
            dictionary[word]|={numStrList[n][0]} 
    n = n+1         

其次,您的while 条件过于严格。 n &lt; len(strlist) 很好。

【讨论】:

  • 你的 strlist 中的元素并不总是拆分为与 strlist 中的元素数量相同的元素,是吗? `你是什么意思,我猜m 可能会有所不同,是吗?但你能改写吗?英语不是我的母语。非常感谢您顺便回答。当您告诉我先拆分字符串时,我不确定我是否明白您的意思。`
  • 谢谢@jtseng!看起来不错,但由于某种原因,我收到此错误:' File "./inverse_index_lab.py", line 21, in makeInverseIndex for word in numStrList[n][1].split(): NameError: global name 'StrList' is not defined' 即使我确保一切正常,我也会更新顶部。
  • 原来的问题已经回答了。
  • @KaizervonMaanen 我认为这是被误导的拼写问题。
  • @KaizervonMaanen 我还更新了答案,以更好地解释我所说的元素数量。
【解决方案2】:

我没有足够的声誉对您的帖子发表评论,所以我在这里发布答案:

我已将最新代码复制并粘贴到底部(编辑 2),它按预期运行,因此我可以看到两个潜在问题:

1) 你可能忘记缩进你的函数定义 2) 您可能在函数定义中将 strList 大写为 StrList,然后在其他地方声明 StrList。

希望这会有所帮助。

【讨论】:

    【解决方案3】:

    如果你想防止这个错误,你也可以做这样的事情。

    try:
        #The code that causes the issue
    except IndexError:
        pass
    

    【讨论】:

      猜你喜欢
      • 2012-03-04
      • 1970-01-01
      • 1970-01-01
      • 2021-10-01
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 2015-06-20
      相关资源
      最近更新 更多