Python:IndexError:列表索引超出范围错误 [英] Python: IndexError: list index out of range Error

查看:127
本文介绍了Python:IndexError:列表索引超出范围错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已更新,请查看底部!

我被卡住了!我收到IndexError:列表索引超出错误范围.

I am stuck! I get a IndexError: list index out of range Error.

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循环的条件,也会发生这种情况.我不明白这是什么问题.我对此很陌生,所以如果有一块西兰花问你这个问题,就可以解释它.

I don't get it... what causes this? It happens even when I change the conditions of the while loop. I don't get what is the problem. I am pretty new at this, so explain it like you would if a piece of broccoli asked you this question.

谢谢大家,我忘了提及输入示例,我想输入以下内容:

Thanks guys, I forgot to mention examples of input, I want to input something like this:

 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"的地方.它应该有一个庞大的清单.有人有提示吗?我希望它进行迭代并挑选出每个字母,然后为它们分配一个字典值.

so to create a dictionary that shows where in the list you might find a 'A' for example. It should work with a huge list. Do anyone have any tips? I want it to iterate and pick out each letter and then assign them a dictionary value.

编辑第二个:

感谢你们的大力帮助,我的代码看起来像这样:

Thanks to great help from you guys my code looks beautiful like this:

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

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

But I still manage to get this error when I try to run the module:

   >>> 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

我看不出错误的来源.

推荐答案

很高兴看到一些智能蔬菜程序.

Good to see some smart veggies programming.

首先,您的问题.就像@Vasiliy所说的那样,您有3个索引. n没问题,因为您可以使用while条件对其进行保护. 1很好,因为enumerate总是生成2件事.剩下的只是m.这是你的问题.

First, your question. Like @Vasiliy said, you have 3 indices. The n is alright, since you protect it with your while condition. The 1 is fine since enumerate always generates 2 things. That just leaves m. This is your problem.

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

Let's say you have N elements in strlist. For each element e in strlist, you apply split() to it. The number of elements in e.split() is not always equal to N. The while condition for m guards against N, not against len(e.split()), hence the index out of range.

要解决此问题,请先拆分字符串,然后循环遍历.当您使用它时,不妨完全摆脱m,只将字符串分割一次,并获得一些性能.另外,您永远不会重置m,它会越来越大.

To solve this, split the string first, and then loop through it. While you're at it, might as well get rid of m altogether, splitting the string only once, and gain some performance. Plus, you never reset your m, which just grows and grows.

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 < len(strlist)很好.

Second, your while conditions are too restrictive. n < len(strlist) is fine.

这篇关于Python:IndexError:列表索引超出范围错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆